File: Type.cpp

package info (click to toggle)
storm-lang 0.7.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 52,004 kB
  • sloc: ansic: 261,462; cpp: 140,405; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (1943 lines) | stat: -rw-r--r-- 57,540 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
#include "stdafx.h"
#include "Type.h"
#include "Engine.h"
#include "NamedThread.h"
#include "Function.h"
#include "Adapter.h"
#include "Exception.h"
#include "Package.h"
#include "TypeTransform.h"
#include "Core/Str.h"
#include "Core/Handle.h"
#include "Core/Gen/CppTypes.h"
#include "Core/StrBuf.h"
#include "Core/Io/Serialization.h" // for SerializedType
#include "OS/UThread.h"
#include "OS/Future.h"
#include "Utils/Memory.h"

namespace storm {

	const wchar *Type::CTOR = S("__init");
	const wchar *Type::DTOR = S("__destroy");


	static void CODECALL stormDtor(void *object, os::Thread *thread);

	// Set 'type->type' to 'me' while forwarding 'name'. This has to be done before invoking the
	// parent constructor, since that relies on 'engine()' working properly, which is not the case
	// for the first object otherwise.
	static Str *setMyType(Str *name, Type *me, GcType *type, Engine &e) {
		// Set the type properly.
		type->type = me;

		// We need to set the engine as well. Should be the first member of this class.
		OFFSET_IN(me, sizeof(NameSet), Engine *) = &e;

		// Check to see if we succeeded!
		assert(&me->engine == &e, L"Type::engine must be the first data member declared in Type.");

		return name;
	}

	Type::Type(Str *name, TypeFlags flags) :
		NameSet(name),
		engine(RootObject::engine()),
		myGcType(null),
		tHandle(null),
		myTypeFlags(flags & ~typeCpp) {

		init(null);
	}

	Type::Type(Str *name, Array<Value> *params, TypeFlags flags) :
		NameSet(name, params),
		engine(RootObject::engine()),
		myGcType(null),
		tHandle(null),
		myTypeFlags(flags & ~typeCpp) {

		init(null);
	}

	Type::Type(SrcPos pos, Str *name, TypeFlags flags) :
		NameSet(name),
		engine(RootObject::engine()),
		myGcType(null),
		tHandle(null),
		myTypeFlags(flags & ~typeCpp) {

		this->pos = pos;
		init(null);
	}

	Type::Type(SrcPos pos, Str *name, Array<Value> *params, TypeFlags flags) :
		NameSet(name, params),
		engine(RootObject::engine()),
		myGcType(null),
		tHandle(null),
		myTypeFlags(flags & ~typeCpp) {

		this->pos = pos;
		init(null);
	}

	Type::Type(Str *name, Array<Value> *params, TypeFlags flags, Size size) :
		NameSet(name, params),
		engine(RootObject::engine()),
		myGcType(null),
		tHandle(null),
		myTypeFlags(flags | typeCpp),
		mySize(size) {

		if ((flags & typeValue) == 0)
			throw new (this) InternalError(S("Can not use the Type constructor taking a Size to create class types."));
		init(null);
	}

	Type::Type(SrcPos pos, Str *name, Array<Value> *params, TypeFlags flags, Size size) :
		NameSet(pos, name, params),
		engine(RootObject::engine()),
		myGcType(null),
		tHandle(null),
		myTypeFlags(flags | typeCpp),
		mySize(size) {

		if ((flags & typeValue) == 0)
			throw new (this) InternalError(S("Can not use the Type constructor taking a Size to create class types."));
		init(null);
	}

	Type::Type(Str *name, TypeFlags flags, Size size, GcType *gcType, const void *vtable) :
		NameSet(name),
		engine(RootObject::engine()),
		myGcType(gcType),
		tHandle(null),
		myTypeFlags(flags | typeCpp),
		mySize(size) {

		myGcType->type = this;
		init(vtable);
	}

	Type::Type(Str *name, Array<Value> *params, TypeFlags flags, Size size, GcType *gcType, const void *vtable) :
		NameSet(name, params),
		engine(RootObject::engine()),
		myGcType(gcType),
		tHandle(null),
		myTypeFlags(flags | typeCpp),
		mySize(size) {

		myGcType->type = this;
		init(vtable);
	}

	// We need to set myGcType->type first, therefore we call setMyType!
	Type::Type(Engine &e, TypeFlags flags, Size size, GcType *gcType) :
		NameSet(setMyType(null, this, gcType, e)), engine(e), myGcType(gcType),
		tHandle(null), myTypeFlags(typeClass | typeCpp), mySize(size) {

		init(null);
	}

	Type::~Type() {
		GcType *g = myGcType;

		// Make sure we abandon the GcType before we free it by using an atomic op (they imply barriers).
		atomicWrite(myGcType, (GcType *)null);

		// The GC will ignore these during shutdown, when it is crucial not to destroy anything too
		// early.
		engine.gc.freeType(g);
	}

	void Type::init(const void *vtable) {
		assert((myTypeFlags & typeValue) == typeValue || (myTypeFlags & typeClass) == typeClass, L"Invalid type flags!");

		// Generally, we want this on types.
		flags |= namedMatchNoInheritance;

		if (myGcType) {
			if (value())
				myGcType->kind = GcType::tArray;

			// Note: If there was a finalizer specified, we will overwrite it with our own later on anyway.
		}

		if (engine.has(bootTypes))
			vtableInit(vtable);

		if (engine.has(bootTemplates))
			lateInit();
	}

	void Type::vtableInit(const void *vtab) {
		if (value())
			return;

		VTable *vt = new (engine) VTable(this);
		if (myTypeFlags & typeCpp) {
			vt->createCpp(vtab);
		} else if (Type *t = super()) {
			vt->createStorm(t->myVTable);
		} else {
			vt->createStorm(Object::stormType(engine)->myVTable);
		}

		// Write it using atomics. That way we get sane behavior in relation to 'hasVTableOf' which
		// may be called from any point in the system.
		atomicWrite(myVTable, vt);
	}

	void Type::lateInit() {
		NameSet::lateInit();

		if (!chain) {
			chain = new (this) TypeChain(this);
			Type *def = defaultSuper();
			if (def)
				setSuper(def);
		}

		chain->lateInit();

		if (myVTable)
			myVTable->lateInit();
	}

	void Type::addTypeFlag(TypeFlags flags) {
		// Mask out `typeClass` and `typeValue`. Can't change them after creation!
		flags &= ~typeClass;
		flags &= ~typeValue;

		// Also, information from C++ can not be added after the fact.
		flags &= ~typeCpp;
		flags &= ~typeCppPOD;
		flags &= ~typeCppSimple;

		// Finally, it is safe to update our flags.
		myTypeFlags |= flags;
	}

	// Our finalizer.
	static void CODECALL destroyType(void *obj, os::Thread *) {
		Type *t = (Type *)obj;
		t->~Type();
	}

	void Type::makeType(Engine &e, GcType *src) {
		// Find the entry containing OFFSET_OF(Type, myGcType).
		nat myTypePos = Nat(src->count);
		for (nat i = 0; i < src->count; i++) {
			if (src->offset[i] == OFFSET_OF(Type, myGcType)) {
				myTypePos = i;
				break;
			}
		}

		assert(myTypePos < src->count, L"The type definition for a type inheriting from core.lang.Type does not contain an entry for 'myGcType'!");

		// Move elements one step back to make room at location 0.
		for (nat i = myTypePos; i > 0; i--) {
			src->offset[i] = src->offset[i - 1];
		}

		src->offset[0] = OFFSET_OF(Type, myGcType);
		src->kind = GcType::tType;
	}

	Type *Type::createType(Engine &e, const CppType *type) {
		assert(wcscmp(type->name, S("Type")) == 0, L"storm::Type was not found!");
		assert(Size(type->size).current() == sizeof(Type),
			L"The computed size of storm::Type is wrong: " + ::toS(Size(type->size).current()) + L" vs " + ::toS(sizeof(Type)));

		// Generate our layout description for the GC:
		nat entries = 0;
		for (; type->ptrOffsets[entries] != CppOffset::invalid; entries++)
			;

		GcType *t = e.gc.allocType(GcType::tType, null, sizeof(Type), entries);

		// Insert 'myGcType' as the first (special) pointer:
		t->offset[0] = OFFSET_OF(Type, myGcType);

		// Insert the other ones afterwards. The 'ptrOffsets' array should contain the special
		// offset as well, since GcType pointers are garbage collected. If it is not found, we will
		// assert.
		nat pos = 1;
		for (nat i = 0; i < entries; i++) {
			size_t offset = Offset(type->ptrOffsets[i]).current();
			if (offset != OFFSET_OF(Type, myGcType)) {
				assert(pos < entries, L"The entry for 'myGcType' was not found in the type description for core.lang.Type.");
				t->offset[pos++] = Offset(type->ptrOffsets[i]).current();
			}
		}

		// Ensure we're finalized.
		t->finalizer = &destroyType;

		// Now we can allocate the type and let the constructor handle the rest!
		return new (e, t) Type(e, typeClass, Size(type->size), t);
	}

	void Type::setType(Object *onto) const {
		engine.gc.switchType(onto, myGcType);
	}

	Type *Type::defaultSuper() const {
		if (value())
			return null;
		else if (useThread)
			return TObject::stormType(engine);
		else
			return Object::stormType(engine);
	}

	void Type::setSuper(Type *to) {
		setSuper(to, null);
	}

	void Type::setSuper(Type *to, ReplaceTasks *tasks) {
		if (to && (to->typeFlags() & typeFinal)) {
			StrBuf *msg = new (engine) StrBuf();
			*msg << S("Can not inherit the type ") << to->identifier() << S(" since it is marked 'final'.");
			throw new (engine) TypedefError(pos, msg->toS());
		}

		// If 'to' is null: figure out what to inherit from.
		if (!to)
			to = defaultSuper();

		// So that Object does not inherit from TObject.
		if (to == this)
			return;

		// Check so that values only inherit from values, and classes only from classes.
		if (to && value() != to->value()) {
			StrBuf *msg = new (engine) StrBuf();
			*msg << S("The type ") << identifier() << S(" can not extend the type ")
				 << to->identifier() << S(" since one is a value, and the other is not.");
			throw new (engine) TypedefError(pos, msg->toS());
		}

		if (!chain)
			chain = new (this) TypeChain(this);

		// Nothing to do?
		if (to == chain->super())
			return;

		if (to && !to->chain)
			to->chain = new (this) TypeChain(to);

		// Set the type-chain properly.
		Type *prev = super();
		chain->super(to);

		// Notify our old parent of removal of vtable members. We only need to do this for the
		// topmost class we're moving, as all other vtables will be deleted.
		vtableDetachedSuper(prev);

		// Propagate changes to all children.
		updateSuper(tasks);
	}

	void Type::updateSuper(ReplaceTasks *tasks) {
		Type *to = super();

		// Which thread to use?
		Type *tObj = TObject::stormType(engine);
		if (to != null && to->chain != null && tObj->chain != null) {
			if (!to->chain->isA(tObj)) {
				useThread = null;
			} else if (to != tObj) {
				useThread = to->useThread;
			}
			// Propagate to our children.
			notifyThread(useThread);
		}

		// Invalidate the GcType for this type.
		if (myTypeFlags & typeCpp) {
			// Type from C++. Nothing to do.
		} else if (myGcType != null) {
			// We're not a type from C++.
			GcType *old = myGcType;
			myGcType = null;
			engine.gc.freeType(old);

			// Create a new one if we are to generate 'replace' instructions.
			if (tasks)
				tasks->replace(old, gcType());
		}

		// TODO: Invalidate the Layout as well.
		// TODO: Invalidate the handle as well.

		if ((myTypeFlags & typeCpp) != typeCpp && !value()) {
			// Re-initialize the vtable.
			myVTable->createStorm(to->myVTable);
		}

		// Register all functions here and in our children as vtable calls.
		vtableNewSuper();

		// Recurse into children.
		TypeChain::Iter i = chain->children();
		while (Type *c = i.next())
			c->updateSuper(tasks);
	}

	MAYBE(Type *) Type::declaredSuper() const {
		Type *s = super();

		if (s == Object::stormType(engine))
			s = null;
		else if (s == TObject::stormType(engine))
			s = null;

		return s;
	}

	Bool Type::setThread(NamedThread *thread) {
		// Can't set threads for value types.
		if (value())
			return false;

		if (Type *currentSuper = super()) {
			// If the current super-type is something other than the base-class Object, or the base
			// class has a 'useThread' configured, disallow setting the thread here:
			Type *objType = Object::stormType(engine);
			if (isA(objType) && currentSuper != objType) {
				// We inherit indirectly from a class-type. Don't allow introducing TObject.
				return false;
			} else if (isA(TObject::stormType(engine))) {
				// Disallow if the super type has its 'useThread' set:
				if (currentSuper->useThread != null) {
					return false;
				}
			}
		}

		useThread = thread;

		Type *def = defaultSuper();
		// Note: this function is used early enough so that 'chain' may not be initialized.
		if (!chain || !isA(def))
			setSuper(def);

		// Propagate the current thread to any child types.
		notifyThread(thread);

		return true;
	}

	RunOn Type::runOn() {
		if (isA(TObject::stormType(engine))) {
			if (useThread)
				return RunOn(useThread);
			else
				return RunOn(RunOn::runtime);
		} else {
			return RunOn();
		}
	}

	Bool Type::abstract() {
		// Note: We always insert abstract functions in a vtable, even if it is not necessary at the
		// moment. This means that we can simply examine all slots in a vtable to determine if we're
		// abstract or not.
		VTable *vt = vtable();

		// If we don't have a VTable, then the concept of 'abstract' is not meaningful.
		if (!vt)
			return false;

		if (isAbstract != abstractUnknown)
			return isAbstract == abstractYes;

		// If any of the topmost functions are abstract, the entire class is abstract.
		Array<Function *> *fns = vt->allSlots();
		isAbstract = abstractYes;
		for (Nat i = 0; i < fns->count(); i++)
			if (fns->at(i)->fnFlags() & fnAbstract)
				return true;

		isAbstract = abstractNo;
		return false;
	}

	void Type::ensureNonAbstract(SrcPos pos) {
		if (!abstract())
			return;

		// Generate a nice error message...
		StrBuf *msg = new (this) StrBuf();
		*msg << S("The class ") << identifier() << S(" is abstract due to the following members:\n");

		VTable *vt = vtable();
		if (vt) {
			Array<Function *> *fns = vt->allSlots();
			for (Nat i = 0; i < fns->count(); i++)
				if (fns->at(i)->fnFlags() & fnAbstract)
					*msg << S(" ") << fns->at(i)->shortIdentifier() << S("\n");
		}

		throw new (this) InstantiationError(pos, msg->toS());
	}

	void Type::add(Named *item) {
		NameSet::add(item);

		if (Function *f = as<Function>(item)) {
			if (*f->name == CTOR)
				updateCtor(f);
			else if (*f->name == DTOR)
				updateDtor(f);
			else
				vtableFnAdded(f);

			if (tHandle)
				updateHandle(f);
		}

		if ((myTypeFlags & typeCpp) != typeCpp) {
			// Tell the layout we found a new variable!
			if (!layout)
				layout = new (engine) Layout();
			layout->add(item, this);
		}
	}

	Bool Type::remove(Named *item) {
		if (!NameSet::remove(item))
			return false;

		if (Function *f = as<Function>(item)) {
			if (*f->name == CTOR)
				updateCtor(f);
			else if (*f->name == DTOR)
				updateDtor(null);
			else
				vtableFnRemoved(f);
		}

		if ((typeFlags() & typeCpp) != typeCpp) {
			// TODO: Update layout?
		}

		return true;
	}

	Named *Type::createBaseWrapper(Named *fromBase, SimplePart *query, Scope scope) {
		// The problem we are trying to solve here is the following:
		// If we are the first class that defines that we are tied to a specific thread,
		// and we return a function from the base class (e.g. 'toS(StrBuf)'). Then, when
		// calling the returned function, the call mechanisms will see that the thread to
		// use is dynamic (since TObject is thread: any), and therefore insert an unexpected
		// thread switch. To solve this, we detect these cases and transparently insert a
		// wrapper. As of writing, this only happens for TObject -> first class, so it
		// only happens for the functions in TObject.

		// No point in doing anything if we don't have a superclass. We should never get caught here
		// due to how the function is called, but it is nice to be a bit robust.
		Type *super = this->super();
		if (!super)
			return fromBase;

		// First: check if we need to bother doing anything at all.
		// This logic is the same as in 'runOn', but with checks in a slightly different
		// order. This is to avoid calling 'isA' if we know that no thread is specified
		// here. Since we are only interested in the case where a thread is specified,
		// this produces the same result as calling 'runOn'.
		if (!useThread)
			return fromBase;
		if (!isA(TObject::stormType(engine)))
			return fromBase;

		// Similarly, we can check our parent class here directly. We know that both we and our
		// parent is at least a TObject (assuming we *have* a parent). If they have the same idea of
		// which thread to use, then we don't have to do anything. Note that this should be the case
		// if both 'useThread' are non-null.
		if (super->useThread == useThread)
			return fromBase;

		// We are only interested in non-static functions.
		Function *baseFunction = as<Function>(fromBase);
		if (!baseFunction)
			return fromBase;
		if (!baseFunction->isMember())
			return fromBase;

		// Also ignore ctors and dtors:
		if (*baseFunction->name == CTOR || *baseFunction->name == DTOR)
			return fromBase;

		// Note: Some of these paths return 'null' instead of 'fromBase'. These are cases where we
		// have determined that the lookup is likely looking for this particular function from
		// another subclass. As such, we return 'null' to nudge the name lookup logic to find the
		// proper function from the appropriate subclass instead.

		// See if it makes sense to create a wrapper by looking at the first parameter:
		if (query->params->empty())
			return fromBase;
		Type *t = query->params->at(0).type;
		// Note: Letting cases where a parameter is Value() through is deliberate. It lets
		// implementations use Value() as a placeholder in case they do something strange,
		// and would like us to call 'matches' instead.
		if (t && !t->isA(this))
			return null; // See above

		// At this point, we can create the wrapper, add it, and return it.
		Function *wrapper = baseFunction->withDerivedThis(this);
		if (!wrapper) {
			WARNING(L"withDerivedThis failed!");
			return fromBase;
		}

		// Double check if we did not pass the checks previously:
		wrapper->parentLookup(this);
		if (query->matches(wrapper, scope) >= 0) {
			add(wrapper);
			return wrapper;
		} else {
			return null; // See above
		}
	}

	Named *Type::find(SimplePart *part, Scope source) {
		if (Named *n = NameSet::find(part, source))
			return n;

		// Constructors are not inherited.
		if (*part->name == CTOR)
			return null;

		if (Type *s = super())
			return createBaseWrapper(s->find(part, source), part, source);
		else
			return null;
	}

	void Type::notifyThread(NamedThread *thread) {
		useThread = thread;

		if (chain != null) {
			TypeChain::Iter i = chain->children();
			while (Type *c = i.next()) {
				c->notifyThread(thread);
			}
		}
	}

	code::Ref Type::typeRef() {
		if (!selfRef) {
			selfRef = new (engine) NamedSource(this);
			selfRef->setPtr(this);
		}
		return code::Ref(selfRef);
	}

	code::TypeDesc *Type::typeDesc() {
		if (myTypeDesc) {
			// Just return the desc we have. It is an actor anyway.
			return myTypeDesc;
		}

		// We need to create the description. Switch threads if neccessary.
		const os::Thread &t = TObject::associatedThread()->thread();
		if (t != os::Thread::current()) {
			// Switch threads...
			Type *me = this;
			os::Future<code::TypeDesc *> f(os::FutureMode::exclusive);
			os::FnCall<code::TypeDesc *, 1> p = os::fnCall().add(me);
			os::UThread::spawn(address(&Type::typeDesc), true, p, f, &t);
			return f.result(&updateFutureExceptions, null);
		}

		// Double-check so that the desc is not created.
		if (!myTypeDesc)
			myTypeDesc = createTypeDesc();
		return myTypeDesc;
	}

	code::TypeDesc *Type::createTypeDesc() {
		if (!value()) {
			// If we're not a value, then we're a plain pointer.
			return engine.ptrDesc();
		}

		// We need to generate a TypeDesc for this value.
		// First: See if we're a complex type.
		Function *ctor = copyCtor();
		Function *dtor = destructor();

		Bool simple = true;
		if (ctor && !ctor->pure())
			simple = false;
		if (dtor && !dtor->pure())
			simple = false;

		// Complex types are actually fairly simple to handle.
		if (!simple) {
			if (ctor == null) {
				Str *msg = TO_S(this, S("The type ") << identifier()
								<< S(" has a nontrivial destructor, but no constructor."));
				throw new (this) TypedefError(pos, msg);
			}

			code::Ref d = dtor ? dtor->ref() : engine.ref(builtin::fnNull);
			return new (this) code::ComplexDesc(size(), ctor->ref(), d);
		}

		// Generate a proper description of this type!
		return createSimpleDesc();
	}

	code::SimpleDesc *Type::createSimpleDesc() {
		forceLoad();
		Size mySize = size(); // Performs a layout of all variables if neccessary.
		Nat elems = populateSimpleDesc(null);

		if (elems == 0 && mySize != Size()) {
			StrBuf *msg = new (this) StrBuf();
			*msg << identifier();
			*msg << S(": Trying to generate a type description for an empty object ")
				S("with a nonzero size. This is most likely not what you want. There are two possible ")
				S("reasons for why this might happen: Either, you try to access the type description of ")
				S("the type too early, or you are attempting to construct a non-standard type, ")
				S("in which case you should override 'createSimpleDesc' as well.");
			throw new (this) TypedefError(pos, msg->toS());
		}

		code::SimpleDesc *desc = new (this) code::SimpleDesc(mySize, elems);
		populateSimpleDesc(desc);
		// Note: In some cases (notably for C++ types) the desc will not be sorted according to offset.
		// If this is the case, we need to sort it here, as other parts of the system expect it to be sorted.
		desc->sort();
		return desc;
	}

	static void merge(Offset offset, Nat &pos, MAYBE(code::SimpleDesc *) into, code::SimpleDesc *from) {
		if (!into) {
			pos += from->count();
			return;
		}

		for (Nat i = 0; i < from->count(); i++) {
			code::Primitive src = from->at(i);
			into->at(pos++) = src.move(src.offset() + offset);
		}
	}

	Nat Type::populateSimpleDesc(MAYBE(code::SimpleDesc *) into) {
		using namespace code;

		Nat pos = 0;

		if (Type *parent = super()) {
			TypeDesc *desc = parent->typeDesc();
			if (SimpleDesc *s = as<SimpleDesc>(desc))
				storm::merge(Offset(), pos, into, s);
			else
				throw new (this) TypedefError(this->pos,
											S("Can not produce a SimpleDesc when the parent type is not a simple type!"));
		}

		Array<MemberVar *> *vars = variables();
		for (Nat i = 0; i < vars->count(); i++) {
			MemberVar *v = vars->at(i);
			Offset offset = v->rawOffset();
			Value type = v->type;

			if (type.isObject() || type.ref) {
				// This is a pointer to something.
				if (into)
					into->at(pos) = Primitive(primitive::pointer, Size::sPtr, offset);
				pos++;
				continue;
			}

			TypeDesc *original = type.type->typeDesc();
			if (PrimitiveDesc *p = as<PrimitiveDesc>(original)) {
				if (into)
					into->at(pos) = p->v.move(offset);
				pos++;
			} else if (SimpleDesc *s = as<SimpleDesc>(original)) {
				storm::merge(offset, pos, into, s);
			} else if (ComplexDesc *c = as<ComplexDesc>(original)) {
				UNUSED(c);
				throw new (this) TypedefError(this->pos,
											S("Can not produce a SimpleDesc from a type containing a complex type!"));
			} else {
				throw new (this) TypedefError(this->pos,
											TO_S(this, S("Unknown type description: ") << original));
			}
		}

		if (into) {
			assert(pos == into->count(), L"A too small SimpleDesc provided.");
		}

		return pos;
	}

	void Type::doLayout() {
		// Make sure we're fully loaded.
		forceLoad();

		// No layout -> nothing to do.
		if (!layout)
			return;

		// We might as well compute our size while we're at it!
		mySize = layout->doLayout(superSize());

		// Since we have computed our size, it means that we can be instantiated. Because of that,
		// make sure that the destructor is compiled now. Otherwise, it might be compiled during
		// shutdown, which is likely to fail:
		if (Function *dtor = destructor())
			dtor->compile();
	}

	Array<MemberVar *> *Type::variables() const {
		if (layout) {
			return layout->variables();
		} else {
			// Fall back to examining the contents of the NameSet.
			Array<MemberVar *> *result = new (this) Array<MemberVar *>();
			for (Iter i = begin(); i != end(); ++i) {
				if (MemberVar *v = as<MemberVar>(i.v()))
					result->push(v);
			}
			return result;
		}
	}

	Size Type::superSize() {
		if (super())
			return super()->size();

		if (value())
			return Size();

		assert(false, L"We are a class which does not inherit from TObject or Object!");
		return Size();
	}

	Size Type::size() {
		if (mySize != Size())
			return mySize;

		// We need to compute our size. Switch threads if neccessary...
		const os::Thread &t = TObject::associatedThread()->thread();
		if (t != os::Thread::current()) {
			// Switch threads...
			Type *me = this;
			os::Future<Size> f(os::FutureMode::exclusive);
			os::FnCall<Size, 1> p = os::fnCall().add(me);
			os::UThread::spawn(address(&Type::size), true, p, f, &t);
			return f.result(&updateFutureExceptions, null);
		}

		mySize = createSize();

		// Since we have computed our size, it means that we can be instantiated. Because of that,
		// make sure that the destructor is compiled now. Otherwise, it might be compiled during
		// shutdown, which is likely to fail:
		if (Function *dtor = destructor())
			dtor->compile();

		return mySize;
	}

	Size Type::createSize() {
		// Recompute the size!
		forceLoad();
		mySize = superSize();

		// If we do not have a layout, we do not have any variables.
		if (layout) {
			mySize = layout->doLayout(mySize);
		}

		return mySize;
	}

	VTable *Type::vtable() {
		// Don't bother if we're a value or we don't have a vtable yet.
		if (!myVTable || value())
			return null;

		// If we're loaded, then we're good to go!
		if (allLoaded())
			return myVTable;

		// We need to load ourself. Make sure we're running on the proper thread.
		const os::Thread &t = TObject::associatedThread()->thread();
		if (t != os::Thread::current()) {
			// Switch threads...
			Type *me = this;
			os::Future<VTable *> f(os::FutureMode::exclusive);
			os::FnCall<VTable *, 1> p = os::fnCall().add(me);
			os::UThread::spawn(address(&Type::vtable), true, p, f, &t);
			return f.result(&updateFutureExceptions, null);
		}

		// In the proper thread. The only thing we need to do is to make sure that the VTable is
		// populated, which is simply done by issuing a 'forceLoad'. Us intercepting the 'add'
		// function will do all of the dirty work.
		// If we force loading too early, we will not be able to boot... All types used during
		// boot should be properly loaded during boot anyway, so that is fine.
		if (engine.has(bootDone))
			forceLoad();
		return myVTable;
	}

	static void defToS(const void *obj, StrBuf *to) {
		*to << S("<no member toS(StrBuf) or toS()>");
	}

	const Handle &Type::handle() {
		// If we're completely done with the handle, return it immediatly.
		if (tHandle)
			return *tHandle;

		// We need to create the handle. Switch threads.
		const os::Thread &t = TObject::associatedThread()->thread();
		if (t != os::Thread::current()) {
			// Switch threads...
			Type *me = this;
			os::Future<const Handle *> f(os::FutureMode::exclusive);
			os::FnCall<const Handle *, 1> p = os::fnCall().add(me);
			os::UThread::spawn(address(&Type::handle), true, p, f, &t);
			return *f.result(&updateFutureExceptions, null);
		}

		if (!tHandle)
			buildHandle();
		return *tHandle;
	}

	static void CODECALL stormDtor(void *object, os::Thread *thread) {
		Type *t = runtime::typeOf((RootObject *)object);
		if (!t)
			return;

		Type::DtorFn f = t->rawDestructor();
		if (!f)
			return;

		// If shutting down, do not care about threads anymore, as we might not have enough to see
		// if the type is a TObject or not...
		if (!t->engine.has(bootShutdown)) {
			if (t->isA(TObject::stormType(t->engine))) {
				// We might need to switch threads...
				TObject *obj = (TObject *)object;
				Thread *t = obj->associatedThread();
				if (t) {
					os::Thread desired = t->thread();
					if (desired != os::Thread::current()) {
						// We can't execute it on this thread. Tell the GC we need a different one!
						*thread = desired;
						return;
					}
				}
			}
		}

		// If we get here, we shall execute on the current thread.
		(*f)(object);
	}

	void Type::updateDtor(Function *dtor) {
		if (rawDtorRef) {
			rawDtorRef->disable();
			rawDtorRef = null;
		}
		rawDtor = null;

		// Keep 'rawDtor' updated if we have a destructor.
		if (dtor) {
			// Make sure we have a proper finalizer. Needs to be done before the line below,
			// otherwise recursion stops at the first level.
			if (!value())
				updateChildFinalizers();

			// Set 'rawDtor'.
			rawDtorRef = new (this) code::MemberRef(this, OFFSET_OF(Type, rawDtor), dtor->ref(), refContent());
		}
	}

	void Type::updateChildFinalizers() {
		// If we have a destructor already, we don't need to keep recursing.
		if (rawDtor)
			return;

		if (myGcType) {
			myGcType->finalizer = &stormDtor;
		}

		if (chain) {
			TypeChain::Iter i = chain->children();
			while (Type *t = i.next()) {
				t->updateChildFinalizers();
			}
		}
	}

	Type::DtorFn Type::rawDestructor() {
		if (rawDtor)
			return rawDtor;

		if (Type *s = super())
			return s->rawDestructor();

		return null;
	}

	void Type::updateCtor(Function *ctor) {
		// Clear the cache.
		if (rawCtorRef) {
			rawCtorRef->disable();
			rawCtorRef = null;
		}
		rawCtor = null;
	}

	Type::CopyCtorFn Type::rawCopyConstructor() {
		CopyCtorFn r = rawCtor;
		if (r)
			return r;

		// Call on proper thread...
		const os::Thread &t = TObject::associatedThread()->thread();
		if (t != os::Thread::current()) {
			// Wrong thread, switch!
			Type *me = this;
			os::Future<void *> f(os::FutureMode::exclusive);
			os::FnCall<void *, 1> p = os::fnCall().add(me);
			os::UThread::spawn(address(&Type::rawCopyConstructor), true, p, f, &t);
			return (CopyCtorFn)f.result(&updateFutureExceptions, null);
		}

		// Find the copy constructor...
		Function *ctor = copyCtor();
		if (!ctor)
			return null;

		// And keep 'rawCtor' updated.
		rawCtorRef = new (this) code::MemberRef(this, OFFSET_OF(Type, rawCtor), ctor->ref(), refContent());
		return rawCtor;
	}

	void Type::findEquivalentTypes(Named *old, ReplaceContext *ctx) {
		if (Type *o = as<Type>(old))
			ctx->addEquivalence(o, this);
	}

	class TypeCheckDiff : public NameDiff {
	public:
		TypeCheckDiff(Type *type, ReplaceContext *ctx) : type(type), ctx(ctx) {}

		Type *type;

		ReplaceContext *ctx;

		virtual void added(Named *item) {
			if (MemberVar *var = as<MemberVar>(item)) {
				// We currently only support modifying the layout of class types:
				if (type->isValue())
					throw new (item) ReplaceError(item->pos, S("Unable to add member variables to value types."));

				// Check so that we either have an initializer, or that the type in the variable has
				// a default ctor we can use.
				if (!var->initializer() && (var->type.type == null || var->type.type->defaultCtor() == null)) {
					StrBuf *message = new (item) StrBuf();
					*message << S("Unable to add the variable ") << item->name << S(" to ") << type->identifier()
							 << S(" since no initializer was specified, and since the type ")
							 << var->type << S(" does not have a default constructor. Add an initializer and try again.");
					throw new (item) ReplaceError(item->pos, message->toS());
				}
			}
		}
		virtual void added(Template *) { /* We don't care */ }

		virtual void removed(Named *item) {
			if (as<MemberVar>(item)) {
				// At the time being, we don't support removing members. We need to check if they are used first.
				throw new (item) ReplaceError(item->pos, S("Unable to remove member variables from types."));
			}
		}
		virtual void removed(Template *) { /* We don't care */ }

		virtual void changed(Named *old, Named *changed) {
			if (Str *msg = changed->canReplace(old, ctx))
				throw new (changed) ReplaceError(changed->pos, msg);

		}
	};

	MAYBE(Str *) Type::canReplace(Named *old, ReplaceContext *ctx) {
		Type *o = as<Type>(old);
		if (!o)
			return new (this) Str(S("Unable to replace a non-type with a type."));

		// Note: Due to type equivalences, the remainder of the system more or less assumes that all
		// types can be replaced without issues. Therefore, we throw errors if we fail for some
		// reason so that the system does not attempt to simply remove and then add the type.

		// We only need to check for conflicts if the old entity has actually been loaded. If it is
		// not loaded, we can replace it without any issues whatsoever.
		if (!o->allLoaded())
			return null;

		forceLoad();

		if (value() != o->value())
			throw new (this) ReplaceError(pos, S("Can not change classes into values or vice versa."));

		if (super() && !o->super()) {
			throw new (this) ReplaceError(pos, S("Can not introduce a super class."));
		} else if (!super() && o->super()) {
			throw new (this) ReplaceError(pos, S("Can not remove a super class."));
		} else if (super()) {
			if (!ctx->same(super(), o->super()))
				throw new (this) ReplaceError(pos, S("Can not change the super class."));
		}

		TypeCheckDiff diff(this, ctx);
		o->diff(this, diff, ctx);

		return null;
	}

	class TypeReplaceDiff : public NameDiff {
	public:
		TypeReplaceDiff(ReplaceTasks *tasks, ReplaceContext *ctx)
			: tasks(tasks), context(ctx), membersUpdated(false) {}

		ReplaceTasks *tasks;
		ReplaceContext *context;

		Bool membersUpdated;

		virtual void added(Named *item) {
			if (as<MemberVar>(item))
				membersUpdated = true;
		}
		virtual void added(Template *) { /* We don't care */ }

		virtual void removed(Named *item) {
			if (as<MemberVar>(item))
				membersUpdated = true;
		}
		virtual void removed(Template *) { /* We don't care */ }

		virtual void changed(Named *old, Named *changed) {
			// Do the replacement.
			changed->replace(old, tasks, context);

			// If both are variables, see if the offset changed. If so, we need to update the heap.
			if (MemberVar *oldVar = as<MemberVar>(old)) {
				if (MemberVar *newVar = as<MemberVar>(changed)) {
					if (oldVar->rawOffset() != newVar->rawOffset())
						membersUpdated = true;
				}
			}
		}
	};

	static Nat findVar(Array<MemberVar *> *in, MemberVar *item) {
		for (Nat i = 0; i < in->count(); i++) {
			if (*item->name == *in->at(i)->name)
				return i;
		}
		return in->count();
	}

	static Bool hasUpdatedTransform(Type *type, ReplaceTasks *tasks, ReplaceContext *ctx, Bool checkMembers = false) {
		Type *oldType = ctx->normalize(type);
		// No updated transform if the type has not been replaced:
		if (oldType == type)
			return false;

		// See if there is already an added transform for the type. This means that the parent's
		// update ran before us, and it already added a transform for us.
		if (tasks->hasTransformFor(oldType))
			return true;

		// If not, the parent might run after us.

		// If 'checkMembers', we should check members here. This is to actually diff the members in
		// the case the parent runs after a child.
		if (checkMembers) {
			// This is a simple check of members:
			type->doLayout();
			Array<MemberVar *> *oldVars = oldType->variables();
			Array<MemberVar *> *newVars = type->variables();

			if (oldVars->count() != newVars->count())
				return true;
			for (Nat oldI = 0; oldI < oldVars->count(); oldI++) {
				MemberVar *oldVar = oldVars->at(oldI);
				Nat newI = findVar(newVars, oldVar);
				if (newI >= newVars->count())
					return true;

				MemberVar *newVar = newVars->at(newI);
				if (oldVar->rawOffset() != newVar->rawOffset())
					return true;
			}
		}

		// If it was equal here, check the parent as well.
		Type *super = type->super();
		if (!super)
			return false;

		return hasUpdatedTransform(super, tasks, ctx, true);
	}

	void Type::doReplace(Named *old, ReplaceTasks *tasks, ReplaceContext *ctx) {
		Type *o = (Type *)old;

		// Force us to compute our layout now. We need it in the diff.
		size(); // Calls 'doLayout' if it is necessary.

		// Update derived classes (Note: We don't need to update our super class).
		if (o->chain) {
			// Note: Calling 'setSuper' will modify the WeakSet inside o->chain that we use to find
			// all children of the old class. This is not good, as it means that we might miss
			// elements in it (e.g. when two or more elements form a chain in consecutive elements,
			// then deleting the first one will make the map move the second one backwards).
			// Therefore, we need to save the children in a separate array first.
			Array<Type *> *toUpdate = new (this) Array<Type *>();
			TypeChain::Iter iter = o->chain->children();
			while (Type *child = iter.next())
				toUpdate->push(child);

			// Now we can update them all without worrying.
			for (Nat i = 0; i < toUpdate->count(); i++) {
				Type *child = toUpdate->at(i);
				if (child->super() != this)
					child->setSuper(this, tasks);
			}
		}

		// TODO: We might be able to move some of this into NameSet.
		TypeReplaceDiff diff(tasks, ctx);
		o->diff(this, diff, ctx);

		// Update the reference.
		if (o->selfRef) {
			typeRef(); // Make sure it is created in here.
			selfRef->steal(o->selfRef);
			o->selfRef = null;
		}

		// We need to replace references to the old one with references to us.
		tasks->replace(old, this);

		// Also replace handles.
		if (o->tHandle) {
			// For many reference types, the handles are the same.
			if (o->tHandle != &handle())
				tasks->replace(o->tHandle, tHandle);
		}

		// Here, we have two options depending on whether the layout changed or not:
		if (diff.membersUpdated) {
			// Expensive path. We need to rewrite all instances of this type on the heap.
			createTypeTransform(tasks, ctx);
		} else if (!hasUpdatedTransform(this, tasks, ctx)) {
			// Less expensive path. The object did not change, but we need to update the GcType of
			// all objects so that the Type returned is correct, and update the VTables.
			if (o->myGcType)
				tasks->replace(o->myGcType, gcType());
			if (o->myVTable)
				vtable()->replace(o->myVTable, tasks);
		}
	}

	void Type::createTypeTransformRec(ReplaceTasks *tasks, ReplaceContext *ctx) {
		createTypeTransform(tasks, ctx);

		if (!chain)
			return;

		TypeChain::Iter children = chain->children();
		while (Type *t = children.next())
			t->createTypeTransformRec(tasks, ctx);
	}

	void Type::createTypeTransform(ReplaceTasks *tasks, ReplaceContext *ctx) {
		Type *oldType = ctx->normalize(this);
		if (tasks->hasTransformFor(oldType))
			return;

		TypeTransform *tfm = new (this) TypeTransform(oldType, this);
		populateTypeTransform(tfm, ctx);
		tasks->transform(tfm);
	}

	void Type::populateTypeTransform(TypeTransform *tfm, ReplaceContext *ctx) {
		if (Type *s = super())
			s->populateTypeTransform(tfm, ctx);

		Type *oldType = ctx->normalize(this);

		// If this type has not been replaced, we don't have to do anything more.
		if (oldType == this)
			return;

		// No layout for the old type -> declared in C++.
		if (!oldType->layout)
			return;

		// Force the layout to happen now.
		size();
		assert(layout);

		// Find differences between variables here:
		Array<MemberVar *> *oldVars = oldType->layout->variables();
		Array<MemberVar *> *newVars = layout->variables();

		for (Nat oldId = 0; oldId < oldVars->count(); oldId++) {
			MemberVar *oldVar = oldVars->at(oldId);

			Nat newId = findVar(newVars, oldVar);
			if (newId >= newVars->count()) {
				// Not found, register it as a removed variable.
				tfm->removed(oldVar);
			} else {
				// Found, register it as a changed variable.
				tfm->same(oldVar, newVars->at(newId));
			}
		}

		for (Nat newId = 0; newId < newVars->count(); newId++) {
			MemberVar *newVar = newVars->at(newId);

			Nat oldId = findVar(oldVars, newVar);
			if (oldId >= oldVars->count()) {
				// Not found, it is a new variable.
				tfm->added(newVar);
			}
		}
	}

	void Type::useSuperGcType() {
		if (myGcType)
			return;

		Type *s = super();
		assert(s, L"Can not use 'useSuperGcType' without a super class!");

		// DebugBreak();
		mySize = s->size();
		myGcType = engine.gc.allocType(s->gcType());
		myGcType->type = this;
	}

	// Create a GcType from a TypeDesc for a type, assuming no parent class is present and no layout
	// has been initialized (ie. no explicit members).
	static GcType *gcTypeFromDesc(Type *type, code::TypeDesc *desc) {
		Engine &e = type->engine;
		Nat size = type->size().current();
		GcType *result = null;

		if (code::PrimitiveDesc *primitive = as<code::PrimitiveDesc>(desc)) {
			if (primitive->v.kind() == code::primitive::pointer) {
				result = e.gc.allocType(GcType::tArray, type, size, 1);
				result->offset[0] = 0;
			} else {
				result = e.gc.allocType(GcType::tArray, type, size, 0);
			}
		} else if (code::SimpleDesc *simple = as<code::SimpleDesc>(desc)) {
			Nat ptrCount = 0;
			for (Nat i = 0; i < simple->count(); i++) {
				if (simple->at(i).kind() == code::primitive::pointer)
					ptrCount++;
			}

			result = e.gc.allocType(GcType::tArray, type, size, ptrCount);
			Nat offsetAt = 0;
			for (Nat i = 0; i < simple->count(); i++) {
				if (simple->at(i).kind() == code::primitive::pointer)
					result->offset[offsetAt++] = simple->at(i).offset().current();
			}
		} else if (code::ComplexDesc *complex = as<code::ComplexDesc>(desc)) {
			// If we get here, the type should be empty.
			(void)complex;
			result = e.gc.allocType(GcType::tArray, type, size, 0);
		} else {
			throw new (type) InternalError(S("Unsupported type description of a value."));
		}

		assert(result);
		return result;
	}

	const GcType *Type::gcType() {
		// Already created?
		if (myGcType != null)
			return myGcType;

		// We need to create it. Switch threads if neccessary...
		const os::Thread &t = TObject::associatedThread()->thread();
		if (t != os::Thread::current()) {
			// Wrong thread, switch!
			Type *me = this;
			os::Future<const GcType *> f(os::FutureMode::exclusive);
			os::FnCall<const GcType *, 2> p = os::fnCall().add(me);
			os::UThread::spawn(address(&Type::gcType), true, p, f, &t);
			return f.result(&updateFutureExceptions, null);
		}

		// We're on the correct thread. Compute the type!
		assert(value() || (myTypeFlags & typeCpp) != typeCpp, L"C++ types should be given a GcType on creation!");


		// Make sure everything is loaded.
		forceLoad();

		// Compute the GcType for us!
		const GcType *superGc = null;
		Size superSize;
		if (Type *s = super()) {
			superGc = s->gcType();
			superSize = s->size();
		}

		if (!layout) {
			// We do not have any variables of our own.
			if (superGc) {
				myGcType = engine.gc.allocType(superGc);
			} else if (value()) {
				// Look at our TypeDesc to see what we shall do.
				myGcType = gcTypeFromDesc(this, typeDesc());
			} else {
				assert(false, L"We're a non-value not inheriting from Object or TObject!");
			}

		} else {
			// Merge our parent's and our offsets (if we have a parent).
			nat entries = layout->fillGcType(superSize, superGc, null);

			if (value())
				myGcType = engine.gc.allocType(GcType::tArray, this, size().current(), entries);
			else if (superGc)
				myGcType = engine.gc.allocType(GcType::Kind(superGc->kind), this, size().current(), entries);
			else
				assert(false, L"Neither a value nor have a parent!");

			layout->fillGcType(superSize, superGc, myGcType);
		}

		myGcType->type = this;

		// Do we need a destructor?
		if (Function *dtor = destructor())
			updateDtor(dtor);

		return myGcType;
	}

	const GcType *Type::gcArrayType() {
		if (value()) {
			return gcType();
		} else if (useThread) {
			return engine.tObjHandle().gcArrayType;
		} else {
			return &pointerArrayType;
		}
	}

	static void objDeepCopy(void *obj, CloneEnv *env) {
		Object *&o = *(Object **)obj;
		cloned(o, env);
	}

	static void objToS(const void *obj, StrBuf *to) {
		const Object *o = *(const Object **)obj;
		*to << o;
	}

	code::Content *Type::refContent() {
		if (!myContent)
			myContent = new (engine) code::Content();
		return myContent;
	}

	void Type::buildHandle() {
		// Note: It seems that for pure C++ types, we replace the handle that was generated from
		// C++. We could skip doing that in many situations? For example, this happens during boot
		// for NameSet lookups, when Str::hash is loaded, for example.
		bool val = value();

		if (!val) {
			// The above check is not strictly necessary for correctness. However, we crash during
			// boot if we try to access 'chain' too early.
			if (isA(TObject::stormType(engine))) {
				// TObject.
				tHandle = &engine.tObjHandle();
				return;
			}
		}

		RefHandle *h = new (engine) RefHandle(refContent());
		tHandle = h;

		// We need to fill in enough members in 'h' to be able to create the arrays below. Note: We
		// know that 'Value' is simple enough to be copied with memcpy, so it is fine to have a
		// partly initialized handle for 'Value' for a small while.
		if (val) {
			const GcType *g = gcType();
			h->size = g->stride;
			h->locationHash = false;
			h->gcArrayType = g;
			h->toSFn = &defToS;
			handleToS = toSMissing;
		} else {
			// Plain class.
			h->size = sizeof(void *);
			h->locationHash = false;
			h->gcArrayType = &pointerArrayType;
			h->copyFn = null; // Memcpy is OK.
			h->deepCopyFn = &objDeepCopy;
			h->toSFn = &objToS;
			handleToS = toSWithParam;
		}

		// Populate the handle for some types manually. Otherwise, we will not be able to boot
		// properly.
		populateHandle(this, h);


		Scope scope = engine.scope();

		Array<Value> *r = new (engine) Array<Value>(1, thisPtr(this));
		Array<Value> *rr = new (engine) Array<Value>(2, thisPtr(this));
		Array<Value> *vv = new (engine) Array<Value>(2, Value(this));

		// Fill in the rest of the members.
		if (val) {
			// Find constructor.
			if (Function *f = as<Function>(find(CTOR, rr, scope)))
				updateHandle(f);

			// Find destructor.
			if (Function *f = as<Function>(find(DTOR, r, scope)))
				updateHandle(f);

			// Find deepCopy.
			if (Function *f = deepCopyFn())
				updateHandle(f);

			// Find toS.
			Array<Value> *rb = new (engine) Array<Value>(2, thisPtr(this));
			rb->at(1) = Value(StormInfo<StrBuf>::type(engine));

			if (Function *f = as<Function>(find(S("toS"), rb, scope))) {
				updateHandle(f);
			} else {
				// Fall back to a version without the StrBuf parameter:
				rb->pop();
				if (Function *f = as<Function>(find(S("toS"), rb, scope)))
					updateHandle(f);
			}
		}

		// Find hash function.
		if (Function *f = as<Function>(find(S("hash"), r, scope)))
			updateHandle(f);

		// Find equal function.
		if (Function *f = as<Function>(find(S("=="), vv, scope)))
			updateHandle(f);

		// Find less-than function.
		if (Function *f = as<Function>(find(S("<"), vv, scope)))
			updateHandle(f);

		// Find the 'serializedType' function.
		if (Function *f = as<Function>(find(S("serializedType"), new (engine) Array<Value>(), scope)))
			updateHandle(f);

		modifyHandle(h);
	}

	void Type::modifyHandle(Handle *) {}

	// Check if the parameters follow the constraints required for comparison functions (i.e. < and ==) to work.
	static Bool comparisonParams(Type *me, Array<Value> *params) {
		if (params->count() != 2)
			return false;

		Value lhs = params->at(0).asRef();
		Value rhs = params->at(1).asRef();

		return lhs.mayReferTo(me)
			&& rhs.mayReferTo(me);
	}

	void Type::updateHandle(Function *fn) {
		if (!as<const RefHandle>(tHandle)) {
			// This happens if we are a TObject. Then we get a default handle. Without this check,
			// we would crash when a 'hash' function is defined, for example.
			return;
		}

		RefHandle *h = (RefHandle *)tHandle;
		bool val = value();
		Array<Value> *params = fn->params;
		Str *name = fn->name;

		if (fn->isMember()) {
			if (params->count() < 1)
				return;
			bool refThis = params->at(0).ref;

			// Note: We only insert constructors, destructors, etc if they are not pure. Pure
			// functions imply that they do mostly nothing, and we might as well use a large scale
			// memcpy in containers etc.
			if (val && *name == CTOR) {
				if (refThis && params->count() == 2 && params->at(1) == Value(this, true) && !fn->pure()) {
					h->setCopyCtor(fn->ref());
				}
			} else if (val && *name == DTOR) {
				if (refThis && params->count() == 1 && !fn->pure()) {
					h->setDestroy(fn->ref());
				}
			} else if (val && *name == S("deepCopy")) {
				if (refThis && params->count() == 2 && params->at(1) == Value(CloneEnv::stormType(engine)) && !fn->pure()) {
					h->setDeepCopy(fn->ref());
				}
			} else if (*name == S("hash")) {
				if (params->count() == 1) {
					if (allRefParams(fn))
						h->setHash(fn->ref());
					else
						h->setHash(makeRefParams(fn));
				}
			} else if (*name == S("==")) {
				if (comparisonParams(this, params)) {
					if (allRefParams(fn))
						h->setEqual(fn->ref());
					else
						h->setEqual(makeRefParams(fn));
				}
			} else if (*name == S("<")) {
				if (comparisonParams(this, params)) {
					if (allRefParams(fn))
						h->setLess(fn->ref());
					else
						h->setLess(makeRefParams(fn));
				}
			} else if (val && *name == S("toS")) {
				if (refThis && params->count() == 2) {
					if (Value(StrBuf::stormType(engine)).mayStore(params->at(1)) && !params->at(1).ref) {
						h->setToS(fn->ref());
						handleToS = toSWithParam;
					}
				} else if (refThis && params->count() == 1 && handleToS != toSWithParam) {
					h->setToS(makeToSThunk(fn));
					handleToS = toSNoParam;
				}
			}
		} else {
			if (*name == S("serializedType") && fn->result.type == StormInfo<SerializedType>::type(engine)) {
				h->setSerializedType(fn->ref());
			}
		}
	}

	Named *Type::findHere(SimplePart *part, Scope source) {
		return NameSet::find(part, source);
	}

	Named *Type::tryFindHere(SimplePart *part, Scope source) {
		return NameSet::tryFind(part, source);
	}

	void Type::toS(StrBuf *to) const {
		if (value()) {
			*to << S("value ");
		} else {
			*to << S("class ");
		}

		if (params)
			*to << new (this) SimplePart(name, params);
		else
			*to << new (this) SimplePart(name);

		bool extends = false;
		if (chain != null && chain->super() != null) {
			if (chain->super() == TObject::stormType(engine)) {
			} else if (chain->super() == Object::stormType(engine)) {
			} else {
				extends = true;
				*to << S(" extends ") << chain->super()->identifier();
			}
		}

		if (useThread && !extends) {
			*to << S(" on ") << useThread->identifier();
		}

		*to << S(" [");
		putVisibility(to);
		*to << S("]");
	}

	Function *Type::defaultCtor() {
		return as<Function>(find(CTOR, new (this) Array<Value>(1, thisPtr(this)), engine.scope()));
	}

	Function *Type::copyCtor() {
		return as<Function>(find(CTOR, new (this) Array<Value>(2, thisPtr(this)), engine.scope()));
	}

	Function *Type::assignFn() {
		return as<Function>(find(S("="), new (this) Array<Value>(2, thisPtr(this)), engine.scope()));
	}

	Function *Type::deepCopyFn() {
		Array<Value> *params = valList(engine, 2, thisPtr(this), Value(CloneEnv::stormType(engine)));
		return as<Function>(find(S("deepCopy"), params, engine.scope()));
	}

	Function *Type::destructor() {
		return as<Function>(find(DTOR, new (this) Array<Value>(1, thisPtr(this)), engine.scope()));
	}

	Function *Type::readRefFn() {
		if (readRef)
			return readRef;

		if (!value()) {
			// We can just use the default implementation shared between all objects.
			if (isA(TObject::stormType(engine)))
				return engine.readTObjFn();
			else
				return engine.readObjFn();
		}

		// Otherwise, we need to create our own function. Note: We're not actually adding the
		// function to the name tree. We want it to be invisible!
		Value r(this);
		code::Listing *src = new (engine) code::Listing(false, typeDesc());
		code::Var param = src->createParam(engine.ptrDesc());

		*src << code::prolog();
		*src << code::fnRetRef(param);

		readRef = dynamicFunction(engine, r, S("_read_"), valList(engine, 1, r.asRef()), src);
		readRef->parentLookup(engine.package());
		return readRef;
	}

	void *Type::operator new(size_t size, Engine &e, GcType *type) {
		assert(size <= type->stride, L"Invalid type description found!");
		return e.gc.alloc(type);
	}

	void Type::operator delete(void *mem, Engine &e, GcType *type) {}

	RootObject *alloc(Type *t) {
		Function *ctor = t->defaultCtor();
		if (!ctor) {
			Str *msg = TO_S(t, S("Can not create ") << t->identifier() << S(", no default constructor."));
			throw new (t) InternalError(msg);
		}
		void *data = runtime::allocObject(t->size().current(), t);
		typedef void *(*Fn)(void *);
		Fn fn = (Fn)ctor->ref().address();
		(*fn)(data);
		return (RootObject *)data;
	}


	/**
	 * VTable logic.
	 *
	 * Note: there is a small optimization we do here. If we know we are the leaf class for a
	 * specific function, that function only needs to be registered in the vtable but does not need
	 * to use vtable dispatch!
	 */

	void Type::vtableFnAdded(Function *fn) {
		// If we are a value, we do not have a vtable.
		if (value())
			return;

		// If the function is a static function, don't use it in vtables.
		if (!fn->isMember())
			return;

		bool abstractFn = (fn->fnFlags() & fnAbstract) == fnAbstract;
		if (abstractFn)
			invalidateAbstract();

		OverridePart *part = new (engine) OverridePart(fn);
		bool insert = false;

		// Try to find a function which overrides this function, or a function which we override. If
		// we found the function in either direction, we do not need to search in the other
		// direction, as they already are in the vtable in that case.
		if (vtableInsertSuper(part, fn)) {
			insert = true;
		} else if (fn->fnFlags() & fnOverride) {
			Str *msg = TO_S(this, S("The function ") << fn->identifier() << S(" is marked 'override' but does not override."));
			throw new (this) TypedefError(fn->pos, msg);
		}

		// Always check subclasses in the case of a function marked 'final'.
		if (!insert || (fn->fnFlags() & fnFinal)) {
			insert |= vtableInsertSubclasses(part, fn);
		}

		// Furthermore, if 'fn' is abstract, we insert it anyway since we're certain it will be used
		// eventually. Furthermore, it greatly simplifies (and speeds up) the implementation of 'abstract()'.
		insert |= abstractFn;

		if (insert)
			myVTable->insert(fn);
	}

	void Type::vtableFnRemoved(Function *fn) {
		// If we are a value, we do not have a vtable.
		if (value())
			return;

		// Don't care if it is a static function.
		if (!fn->isMember())
			return;

		// See if we can remove the function from the vtable.
		if (myVTable)
			myVTable->remove(fn);

		// TODO: Check if any 'abstract' and 'override' constraints were broken.
	}

	// See if the return type of a function matches the super function.
	// If the result differs "too much" in some sense, the calling conventions of the two functions
	// will differ, and we will either produce weird results or crash.
	static bool checkResult(Function *parent, Function *child) {
		Value p = parent->result;
		Value c = child->result;

		if (p.type == null) {
			// void only allows void
			return c.type == null;
		} else if (p.isValue() && !p.ref) {
			// We can't support inheritance in values, since that could potentially overwrite memory in the caller.
			// If we're returning a reference, the situation is different. Then we treat values as if they were
			// regular object types.
			return p.type == c.type;
		} else {
			// Object, actor or reference. Regular inheritance rules apply.
			return p.mayReferTo(c.type);
		}
	}

	// See if the function 'child' is allowed to override 'parent'.
	static void checkOverride(Function *parent, Function *child) {
		if (parent->fnFlags() & fnFinal) {
			Str *msg = TO_S(parent, S("The function ") << child->identifier() << S(" attempts to ")
							S("override the final function ") << parent->identifier() << S("."));
			throw new (parent) TypedefError(child->pos, msg);
		}

		if (!checkResult(parent, child)) {
			Str *msg = TO_S(parent, S("The function ") << child->identifier() << S(" overrides ")
							<< parent->identifier() << S(", but the return types are not compatible. ")
							<< S("Got ") << child->result << S(", but expected a type compatible with ")
							<< parent->result << S("."));
			throw new (parent) TypedefError(child->pos, msg);
		}
	}

	Bool Type::vtableInsertSuper(OverridePart *fn, Function *original) {
		// See if our parent contains an appropriate function.
		Type *s = super();
		if (!s)
			return false;

		Function *found = as<Function>(s->tryFindHere(fn, Scope()));
		if (found && found->visibleFrom(original)) {
			// Is this allowed?
			checkOverride(found, original);

			// Found it, no need to search further as all possible parent functions are in the
			// vtable already.
			s->myVTable->insert(found);
			return true;
		} else {
			return s->vtableInsertSuper(fn, original);
		}
	}

	Bool Type::vtableInsertSubclasses(OverridePart *fn, Function *original) {
		bool inserted = false;

		TypeChain::Iter i = chain->children();
		while (Type *child = i.next()) {
			// Note: We do not want to eagerly load the child class now. The VTable for the child is
			// not needed until it is instantiated anyway, and we will get notified when that happens.
			Function *found = as<Function>(child->tryFindHere(fn, Scope()));
			if (found && original->visibleFrom(found)) {
				// Found something. Is it allowed?
				checkOverride(original, found);

				// Insert it in the vtable. We do not need to go further down this particular path
				// as any overriding functions there are already found by now.
				child->myVTable->insert(found);
				inserted = true;
			} else {
				inserted |= child->vtableInsertSubclasses(fn, original);
			}
		}

		return inserted;
	}

	void Type::vtableNewSuper() {
		// Insert all functions in here and in our super-classes.
		for (Iter i = begin(), e = end(); i != e; ++i) {
			Function *f = as<Function>(i.v());
			if (!f)
				continue;
			if (*f->name == CTOR)
				continue;

			vtableFnAdded(f);
		}

		isAbstract = abstractUnknown;
	}

	void Type::vtableDetachedSuper(Type *old) {
		if (!old)
			return;

		if (!engine.has(bootTemplates))
			return;

		if (old->myVTable)
			old->myVTable->removeChild(this);
		isAbstract = abstractUnknown;
	}

	void Type::invalidateAbstract() {
		isAbstract = abstractUnknown;

		TypeChain::Iter i = chain->children();
		while (Type *child = i.next())
			child->invalidateAbstract();
	}

}