generics1.icl 115 KB
Newer Older
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
//**************************************************************************************
// Generic programming features 
//**************************************************************************************

implementation module generics1

import StdEnv
import check
from checktypes import createClassDictionaries
/*2.0
from transform import ::Group
0.2*/
//1.3
from transform import Group
//3.1

import genericsupport

//**************************************************************************************
// Data types
//**************************************************************************************

:: FunDefs :== {#FunDef}
:: Modules :== {#CommonDefs}
:: DclModules :== {#DclModule}
:: Groups :== {!Group}
:: FunsAndGroups :== (!Index, !Index, ![FunDef], ![Group])

//**************************************************************************************
// Exported functions
//**************************************************************************************

convertGenerics :: 
		!Int 					// index of the main dcl module
		!NumberSet				// set of used modules
		!{#CommonDefs} 			// common definitions of all modules
		!{!Group} 				// groups of functions
		!*{# FunDef} 			// functions
		!*TypeDefInfos 			// type definition information of all modules
		!*Heaps 				// all heaps
		!*HashTable 			// needed for what creating class dictionaries
		!*PredefinedSymbols 	// predefined symbols
		!u:{# DclModule}		// dcl modules
		!*ErrorAdmin 			// to report errors
	->  ( !{#CommonDefs}		// common definitions of all modules
		, !{!Group}				// groups of functions
		, !*{# FunDef}			// function definitions
		, ![IndexRange]			// index ranges of generated functions
		, !*TypeDefInfos		// type definition infos
		, !*Heaps				// all heaps
		, !*HashTable			// needed for creating class dictinaries
		, !*PredefinedSymbols	// predefined symbols	
		, !u:{# DclModule}		// dcl modules
		, !*ErrorAdmin			// to report errors
		)
convertGenerics
		main_dcl_module_n 
		used_module_numbers
		modules 
		groups 
		funs 
		td_infos 
		heaps
		hash_table 
		u_predefs 
		dcl_modules 
		error

	//#! td_infos = td_infos ---> "************************* generic phase started ******************** "
	//#! funs = dump_funs 0 funs
	//#! dcl_modules = dump_dcl_modules 0 dcl_modules
		
	#! modules = {x \\ x <-: modules} 			// unique copy
	#! dcl_modules = { x \\ x <-: dcl_modules } 	// unique copy
	#! size_predefs = size u_predefs
	#! (predefs, u_predefs) = arrayCopyBegin u_predefs size_predefs // non-unique copy

	#! td_infos = clearTypeDefInfos td_infos
		//---> ("used module numbers ", main_dcl_module_n, numberSetToList used_module_numbers)
	#! (modules, heaps) = clearGenericDefs modules heaps 

	#! (iso_range, funs, groups, td_infos, modules, heaps, error)
		= buildGenericRepresentations 
			(main_dcl_module_n /*---> "====================== call buildGenericRepresentations"*/)
			predefs 
			funs groups td_infos modules heaps error
	| not error.ea_ok
		= (modules, groups, funs, [], td_infos, heaps, hash_table, u_predefs, dcl_modules, error)

	// build classes for each kind of each generic function
	#! (modules, dcl_modules, heaps, symbol_table, td_infos, error) 
		= buildClasses 
				main_dcl_module_n used_module_numbers 
				modules dcl_modules heaps hash_table.hte_symbol_heap td_infos error
			//---> ("====================== call buildClasses")
	#! hash_table = { hash_table & hte_symbol_heap = symbol_table }	
	| not error.ea_ok
		= (modules, groups, funs, [], td_infos, heaps, hash_table, u_predefs, dcl_modules, error)

	#! (instance_range, funs, groups, modules, dcl_modules, td_infos, heaps, error)
		= convertGenericCases main_dcl_module_n used_module_numbers predefs funs groups modules dcl_modules td_infos heaps error
			//---> ("====================== call convertGenericCases")

	| not error.ea_ok
		= (modules, groups, funs, [], td_infos, heaps, hash_table, u_predefs, dcl_modules, error)
	
	//#! funs = dump_funs 0 funs
	//#! dcl_modules = dump_dcl_modules 0 dcl_modules
	//#! error = error ---> "************************* generic phase completed ******************** "
	//| True = abort "generic phase aborted for testing\n"		
	= (modules, groups, funs, [iso_range, instance_range], td_infos, heaps, hash_table, u_predefs, dcl_modules, error)
where

	dump_funs n funs 
		| n == size funs
			= funs
			#! ({fun_symb, fun_type, fun_body}, funs) = funs ! [n]
			#! funs = funs
				//---> ("icl function ", fun_symb, n, fun_type, fun_body) 
			=  dump_funs (inc n) funs
	dump_dcl_modules n dcl_modules
		| n == size dcl_modules
			= dcl_modules			
			# ({dcl_functions}, dcl_modules) = dcl_modules ! [n]				
			= dump_dcl_modules (inc n) (dump_dcl_funs 0 dcl_functions dcl_modules)
				//---> ("dcl module", n)		
	dump_dcl_funs n dcl_funs dcl_modules
		| n == size dcl_funs
			= dcl_modules
			# {ft_symb, ft_type} = dcl_funs.[n]
			= dump_dcl_funs (inc n) dcl_funs dcl_modules
				//---> ("dcl function", ft_symb, n, ft_type)


//****************************************************************************************
// clear stuff that might have been left over
// from compilation of other icl modules
//****************************************************************************************

clearTypeDefInfos td_infos
	= clear_modules 0 td_infos
where
	clear_modules n td_infos
		| n == size td_infos
			= td_infos
			#! (td_infos1, td_infos) = replace td_infos n {}
			#! td_infos1 = clear_td_infos 0 td_infos1
			#! (_, td_infos) = replace td_infos n td_infos1
			= clear_modules (inc n) td_infos 
			
	clear_td_infos n td_infos 			
		| n == size td_infos
			= td_infos
			#! (td_info, td_infos) = td_infos![n]
			#! td_infos = {td_infos & [n] = {td_info & tdi_gen_rep = No}}
			= clear_td_infos (inc n) td_infos 

clearGenericDefs modules heaps
	= clear_module 0 modules  heaps
where	
	clear_module n modules heaps
		| n == size modules
			= (modules, heaps)
			#! ({com_generic_defs}, modules) = modules![n]
			#! (com_generic_defs, heaps) = updateArraySt clear_generic_def {x\\x<-:com_generic_defs} heaps 			
			#! modules = {modules & [n].com_generic_defs = com_generic_defs}
			= clear_module (inc n) modules heaps
			
	clear_generic_def _ generic_def=:{gen_name,gen_info_ptr} heaps=:{hp_generic_heap}
		#! (gen_info, hp_generic_heap) = readPtr gen_info_ptr hp_generic_heap
		#! gen_info = 
			{ gen_info 
			& gen_cases = []
			, gen_classes = createArray 32 []
			}	
		#! hp_generic_heap = writePtr gen_info_ptr gen_info hp_generic_heap
		= (generic_def, {heaps & hp_generic_heap = hp_generic_heap})
		
//****************************************************************************************
//	generic type representation
//****************************************************************************************

// generic representation is built for each type argument of
// generic cases of the current module
buildGenericRepresentations ::
		!Index
		!PredefinedSymbols
		!*FunDefs
		!Groups
		!*TypeDefInfos
		!*Modules
		!*Heaps
		!*ErrorAdmin
	->	( !IndexRange
		, !*FunDefs
		, !Groups
		, !*TypeDefInfos
		, !*Modules
		, !*Heaps
		, !*ErrorAdmin
		) 
buildGenericRepresentations main_module_index predefs funs groups td_infos modules heaps error
	
	#! size_funs = size funs
	#! size_groups = size groups
	#! ({com_gencase_defs}, modules) = modules ! [main_module_index]
			
	#! ((new_fun_index, new_group_index, new_funs, new_groups), td_infos, modules, heaps, error) 
		= foldArraySt on_gencase com_gencase_defs ((size_funs, size_groups, [], []), td_infos, modules, heaps, error)

	#! funs = arrayPlusRevList funs new_funs
	#! groups = arrayPlusRevList groups new_groups

	#! range = {ir_from = size_funs, ir_to = new_fun_index}

	= (range, funs, groups, td_infos, modules, heaps, error)
where 

	on_gencase index case_def=:{gc_type_cons,gc_name} st
		= build_generic_rep_if_needed gc_type_cons st 

	build_generic_rep_if_needed :: 
			!TypeCons !((!Index,!Index,![FunDef],![Group]), !*TypeDefInfos, !*{#CommonDefs}, !*Heaps, !*ErrorAdmin)	
		->  (!(!Index, !Index, ![FunDef], ![Group]), !*TypeDefInfos, !*{#CommonDefs}, !*Heaps, !*ErrorAdmin)
	build_generic_rep_if_needed (TypeConsSymb {type_index={glob_module,glob_object}, type_name}) (funs_and_groups, td_infos, modules, heaps, error)
		#! (type_def, modules) = modules![glob_module].com_type_defs.[glob_object]
		#! (td_info, td_infos) = td_infos![glob_module, glob_object]
		#! type_def_gi = {gi_module=glob_module,gi_index=glob_object}
		= case td_info.tdi_gen_rep of
			Yes _ 
				-> (funs_and_groups, td_infos, modules, heaps, error)
					//---> ("generic representation is already built", type_name)
			No 
				#! (gen_type_rep, funs_and_groups, modules, heaps, error)
					= buildGenericTypeRep type_def_gi main_module_index predefs funs_and_groups modules heaps error
							
				#! td_info = {td_info & tdi_gen_rep = Yes gen_type_rep}
				#! td_infos = {td_infos & [glob_module, glob_object] = td_info} 
				-> (funs_and_groups, td_infos, modules, heaps, error)					
					//---> ("build generic representation", type_name)
	build_generic_rep_if_needed _ st = st 
	
buildGenericTypeRep :: 
		!GlobalIndex 			// type def index
		!Index 					// main module index 
		!PredefinedSymbols 	
		!(!Index,!Index,![FunDef],![Group]) 
		!*{#CommonDefs} 
		!*Heaps 
		!*ErrorAdmin 
	->	( !GenericTypeRep
		, !(!Index, !Index, ![FunDef], ![Group])
		, !*{#CommonDefs} 
		, !*Heaps
		, !*ErrorAdmin
		)
buildGenericTypeRep type_index main_module_index predefs funs_and_groups modules heaps error
	# (type_def, modules) = modules![type_index.gi_module].com_type_defs.[type_index.gi_index]
	# (atype, modules,error) = buildStructureType type_index predefs modules error
	
	# (from_fun_ds, funs_and_groups, heaps, error)
		= buildConversionFrom type_index.gi_module type_def main_module_index predefs funs_and_groups heaps error

	# (to_fun_ds, funs_and_groups, heaps, error)
		= buildConversionTo type_index.gi_module type_def main_module_index predefs funs_and_groups heaps error

	# (iso_fun_ds, funs_and_groups, heaps, error)
		= buildConversionIso type_def from_fun_ds to_fun_ds main_module_index predefs funs_and_groups heaps error

	= ({gtr_type=atype,gtr_iso=iso_fun_ds}, funs_and_groups, modules, heaps, error)
		//---> ("buildGenericTypeRep", type_def.td_name, atype)
	
//========================================================================================
//	the structure type
//========================================================================================

buildStructureType :: 
		!GlobalIndex				// type definition module 
		!PredefinedSymbols
		!*{#CommonDefs}
		!*ErrorAdmin
	-> 	( !AType			// the structure type
		, !*{#CommonDefs}
		, !*ErrorAdmin
		)
buildStructureType {gi_module,gi_index} predefs modules error
	# (type_def=:{td_name}, modules) = modules![gi_module].com_type_defs.[gi_index]	
	# (common_defs, modules) = modules ! [gi_module]	
	# (atype, error) = build_type type_def common_defs error	
	= (atype, modules, error)
		//---> ("buildStructureType", td_name, atype)	
where 
	build_type {td_rhs=(AlgType alts)} common_defs error
		# cons_defs = [common_defs.com_cons_defs.[ds_index] \\ {ds_index} <- alts]
		# cons_args = [buildProductType cons_def.cons_type.st_args predefs \\ cons_def <- cons_defs]
		= (buildSumType cons_args predefs, error) 	
	build_type {td_rhs=(RecordType {rt_constructor={ds_index}})} common_defs error
		# cons_def = common_defs.com_cons_defs.[ds_index]
		= (buildProductType cons_def.cons_type.st_args predefs, error)
	build_type {td_rhs=(SynType type)} common_defs error
		= (type /* is that correct ???*/, error)
	build_type td=:{td_rhs=(AbstractType _),td_name, td_arity, td_args, td_pos} common_defs error
		= (makeAType TE TA_Multi, 
			reportError td_name td_pos "cannot build a generic representation of an abstract type" error)
		
// build a product of types
buildProductType :: ![AType] !PredefinedSymbols -> !AType
buildProductType types predefs 
	= listToBin build_pair build_unit types
where
	build_pair x y = buildPredefTypeApp PD_TypePAIR [x, y] predefs	
	build_unit  = buildPredefTypeApp PD_TypeUNIT [] predefs

// build a sum of types		
buildSumType :: ![AType] !PredefinedSymbols -> !AType
buildSumType types predefs 
	= listToBin build_either build_void types
where
	build_either x y = buildPredefTypeApp PD_TypeEITHER [x, y] predefs	
	build_void  = abort "sum of zero types\n"

// build a binary representation of a list
listToBin :: (a a -> a) a [a] -> a 
listToBin bin tip [] = tip
listToBin bin tip [x] = x
listToBin bin tip xs
	# (l,r) = splitAt ((length xs) / 2) xs
	= bin (listToBin bin tip l) (listToBin bin tip r)

// build application of a predefined type constructor 
buildPredefTypeApp :: !Int [AType] !PredefinedSymbols -> !AType
buildPredefTypeApp predef_index args predefs
	# {pds_module, pds_def} = predefs.[predef_index]
	# pds_ident = predefined_idents.[predef_index]
	# global_index = {glob_module = pds_module, glob_object = pds_def}
	# type_symb = MakeTypeSymbIdent global_index pds_ident (length args) 		  
	= makeAType (TA type_symb args) TA_Multi

//========================================================================================
//	conversions functions
//========================================================================================

// buildConversionIso
buildConversionIso :: 
		!CheckedTypeDef		// the type definition
		!DefinedSymbol		// from fun
		!DefinedSymbol	 	// to fun
		!Index				// main module
		!PredefinedSymbols		
		(!Index, !Index, ![FunDef], ![Group])
		!*Heaps
		!*ErrorAdmin
	-> 	( !DefinedSymbol
		, (!Index, !Index, ![FunDef], ![Group])
		, !*Heaps
		, !*ErrorAdmin
		)
buildConversionIso 
		type_def=:{td_name, td_pos}
		from_fun 
		to_fun
		main_dcl_module_n
		predefs
		funs_and_groups
		heaps 
		error
	#! (from_expr, heaps) 	= buildFunApp main_dcl_module_n from_fun [] heaps
	#! (to_expr, heaps) 	= buildFunApp main_dcl_module_n to_fun [] heaps	
	#! (iso_expr, heaps) 	= build_iso to_expr from_expr heaps
	
	#! ident = makeIdent ("iso" +++ td_name.id_name)
	#! (def_sym, funs_and_groups) = buildFunAndGroup ident [] iso_expr No main_dcl_module_n td_pos funs_and_groups
	= (def_sym, funs_and_groups, heaps, error)
		//---> ("buildConversionIso", td_name, let (_,_,fs,_) = funs_and_groups in hd fs)
where
	build_iso to_expr from_expr heaps 
		= buildPredefConsApp PD_ConsBimap [to_expr, from_expr] predefs heaps	
		
// conversion from type to generic
buildConversionTo ::
		!Index				// type def module
		!CheckedTypeDef 	// the type def
		!Index 				// main module
		!PredefinedSymbols
		!(!Index, !Index, ![FunDef], ![Group])
		!*Heaps	
		!*ErrorAdmin
	-> 	( !DefinedSymbol
		, (!Index, !Index, ![FunDef], ![Group])
		, !*Heaps
		, !*ErrorAdmin	
		)
buildConversionTo		
		type_def_mod 
		type_def=:{td_rhs, td_name, td_index, td_pos} 
		main_module_index
		predefs
		funs_and_groups
		heaps
		error
	# (arg_expr, arg_var, heaps) = buildVarExpr "x" heaps 
	# (body_expr, heaps, error) = 
		build_expr_for_type_rhs type_def_mod td_index td_rhs arg_expr heaps error
	# fun_name = makeIdent ("fromGenericTo" +++ td_name.id_name)
	| not error.ea_ok
		# (def_sym, funs_and_groups) 
			= (buildFunAndGroup fun_name [] EE No main_module_index td_pos funs_and_groups)
		= (def_sym, funs_and_groups, heaps, error)	
			//---> ("buildConversionTo failed", td_name)
		# (def_sym, funs_and_groups) 
			= (buildFunAndGroup fun_name [arg_var] body_expr No main_module_index td_pos funs_and_groups)
		= (def_sym, funs_and_groups, heaps, error)
			//---> ("buildConversionTo", td_name, let (_,_,fs,_) = funs_and_groups in hd fs)
where
	// build conversion for type rhs
	build_expr_for_type_rhs :: 
			!Int 				// type def module
			!Int 				// type def index 
			!TypeRhs			// type def rhs 
			!Expression			// expression of the function argument variable   
			!*Heaps 
			!*ErrorAdmin
		-> 	( !Expression		// generated expression
			, !*Heaps	// state
			, !*ErrorAdmin
			)
 	build_expr_for_type_rhs type_def_mod type_def_index (AlgType def_symbols) arg_expr heaps error
		= build_expr_for_conses type_def_mod type_def_index def_symbols arg_expr heaps error
	build_expr_for_type_rhs type_def_mod type_def_index (RecordType {rt_constructor}) arg_expr heaps error		
		= build_expr_for_conses type_def_mod type_def_index [rt_constructor] arg_expr  heaps error
	build_expr_for_type_rhs type_def_mod type_def_index (AbstractType _) arg_expr  heaps error
		#! error = checkErrorWithIdentPos (newPosition td_name td_pos) "cannot build isomorphisms for an abstract type" error
		= (EE, heaps, error)
	build_expr_for_type_rhs type_def_mod type_def_index (SynType _) arg_expr  heaps error
		#! error = checkErrorWithIdentPos (newPosition td_name td_pos) "cannot build isomorphisms for a synonym type" error
		= (EE, heaps, error)
	
	// build conversion for constructors of a type def 	
	build_expr_for_conses type_def_mod type_def_index cons_def_syms arg_expr heaps error
		# (case_alts, heaps, error) = 
			build_exprs_for_conses 0 (length cons_def_syms) type_def_mod cons_def_syms  heaps error
		# case_patterns = AlgebraicPatterns {glob_module = type_def_mod, glob_object = type_def_index} case_alts
		# (case_expr, heaps) = buildCaseExpr arg_expr case_patterns heaps
		= (case_expr, heaps, error)	
			//---> (free_vars, case_expr)		
	
	// build conversions for a constructor 	
	build_exprs_for_conses :: !Int !Int !Int ![DefinedSymbol] !*Heaps !*ErrorAdmin
		-> ([AlgebraicPattern], !*Heaps, !*ErrorAdmin)
	build_exprs_for_conses i n type_def_mod [] heaps error = ([], heaps, error) 	
	build_exprs_for_conses i n type_def_mod [cons_def_sym:cons_def_syms] heaps error
		#! (alt, heaps, error) = build_expr_for_cons i n type_def_mod cons_def_sym heaps error
		#! (alts, heaps, error) =  build_exprs_for_conses (i+1) n type_def_mod cons_def_syms heaps error 		
		= ([alt:alts], heaps, error)
					
	// build conversion for a constructor	
	build_expr_for_cons :: !Int !Int !Int !DefinedSymbol !*Heaps !*ErrorAdmin 
		-> (AlgebraicPattern, !*Heaps, !*ErrorAdmin)
	build_expr_for_cons 	
		i n type_def_mod def_symbol=:{ds_ident, ds_arity}
		heaps error
	
		#! names = ["x" +++ toString (i+1) +++ toString k \\ k <- [1..ds_arity]]
		#! (var_exprs, vars, heaps) = buildVarExprs names heaps 
		#! (expr, heaps) = build_prod var_exprs predefs heaps		
		#! (expr, heaps) = build_sum i n expr predefs heaps
				
		#! alg_pattern = {
			ap_symbol = {glob_module = type_def_mod, glob_object = def_symbol},
			ap_vars = vars,
			ap_expr = expr,
			ap_position = NoPos
			}
		= (alg_pattern, heaps, error)	
	
	build_sum :: !Int !Int !Expression !PredefinedSymbols !*Heaps -> (!Expression, !*Heaps)
	build_sum i n expr predefs heaps
		| n == 0 	= abort "build sum of zero elements\n"
		| i >= n	= abort "error building sum"
		| n == 1 	= (expr, heaps)
		| i < (n/2) 
			# (expr, heaps) = build_sum i (n/2) expr predefs heaps
			= build_left expr heaps
		| otherwise
			# (expr, heaps) = build_sum (i - (n/2)) (n - (n/2)) expr predefs heaps
			= build_right expr heaps
	where
		build_left x heaps = buildPredefConsApp PD_ConsLEFT [x] predefs heaps
		build_right x heaps = buildPredefConsApp PD_ConsRIGHT [x] predefs heaps
				
	build_prod :: ![Expression] !PredefinedSymbols !*Heaps -> (!Expression, !*Heaps)
	build_prod [] predefs heaps = build_unit heaps
	where
		build_unit heaps = buildPredefConsApp PD_ConsUNIT [] predefs heaps 	
	build_prod [expr] predefs heaps = (expr, heaps)
	build_prod exprs predefs heaps
		# (lexprs, rexprs) = splitAt ((length exprs)/2) exprs  
		# (lexpr, heaps) = build_prod lexprs predefs heaps
		# (rexpr, heaps) = build_prod rexprs predefs heaps
		= build_pair lexpr rexpr heaps
	where
		build_pair x y heaps = buildPredefConsApp PD_ConsPAIR [x, y] predefs heaps
			
buildConversionFrom	::	
		!Index				// type def module
		!CheckedTypeDef 	// the type def
		!Index 				// main module
		!PredefinedSymbols
		!(!Index, !Index, ![FunDef], ![Group])
		!*Heaps	
		!*ErrorAdmin
	-> 	( !DefinedSymbol
		, (!Index, !Index, ![FunDef], ![Group])
		, !*Heaps
		, !*ErrorAdmin	
		)
buildConversionFrom		
		type_def_mod 
		type_def=:{td_rhs, td_name, td_index, td_pos} 
		main_module_index
		predefs
		funs_and_groups
		heaps
		error
	# (body_expr, arg_var, heaps, error) = 
		build_expr_for_type_rhs type_def_mod td_rhs heaps error
	# fun_name = makeIdent ("toGenericFrom" +++ td_name.id_name)
	| not error.ea_ok
		# (def_sym, funs_and_groups) 
			= (buildFunAndGroup fun_name [] EE No main_module_index td_pos funs_and_groups)
		= (def_sym, funs_and_groups, heaps, error)	
			//---> ("buildConversionFrom failed", td_name)
		# (def_sym, funs_and_groups) 
			= (buildFunAndGroup fun_name [arg_var] body_expr No main_module_index td_pos funs_and_groups)
		= (def_sym, funs_and_groups, heaps, error)
			//---> ("buildConversionFrom", td_name, let (_,_,fs,_) = funs_and_groups in hd fs)
where
	// build expression for type def rhs
	build_expr_for_type_rhs :: 
			!Index				// type def module
			!TypeRhs			// type rhs
			!*Heaps
			!*ErrorAdmin	
		-> 	( !Expression		// body expresssion
			, !FreeVar
			, !*Heaps
			, !*ErrorAdmin
			)		
	build_expr_for_type_rhs type_def_mod (AlgType def_symbols) heaps error
		= build_sum type_def_mod def_symbols heaps error
	build_expr_for_type_rhs type_def_mod (RecordType {rt_constructor}) heaps error				
		= build_sum type_def_mod [rt_constructor] heaps	error
	build_expr_for_type_rhs type_def_mod (AbstractType _) heaps error
		#! error = reportError td_name td_pos "cannot build isomorphisms for an abstract type" error
		= (EE, undef, heaps, error)
	build_expr_for_type_rhs type_def_mod (SynType _) heaps error
		#! error = reportError td_name td_pos "cannot build isomorphisms for a synonym type" error
		= (EE, undef, heaps, error)
	
	// build expression for sums
	build_sum :: 
			!Index 
			![DefinedSymbol] 
			!*Heaps 
			!*ErrorAdmin
		-> 	( !Expression
			, !FreeVar			// top variable
			, !*Heaps
			, !*ErrorAdmin
			)
	build_sum type_def_mod [] heaps error
		= abort "algebraic type with no constructors!\n"
	build_sum type_def_mod [def_symbol] heaps error
		#! (cons_app_expr, cons_arg_vars, heaps) = build_cons_app type_def_mod def_symbol heaps
		#! (alt_expr, var, heaps) = build_prod cons_app_expr cons_arg_vars heaps 		
		= (alt_expr, var, heaps, error)
	build_sum type_def_mod def_symbols heaps error
		#! (left_def_syms, right_def_syms) = splitAt ((length def_symbols) /2) def_symbols
	
		#! (left_expr, left_var, heaps, error) 
			= build_sum type_def_mod left_def_syms heaps error

		#! (right_expr, right_var, heaps, error) 
			= build_sum type_def_mod right_def_syms heaps error
	
		#! (case_expr, var, heaps) = 
			build_case_either left_var left_expr right_var right_expr heaps
		= (case_expr, var, heaps, error)
	
	// build expression for products
	build_prod :: 
			!Expression   					// result of the case on product
			![FreeVar] 						// list of variables of the constructor pattern
			!*Heaps
		-> 	( !Expression					// generated product
			, !FreeVar						// top variable
			, !*Heaps
			)
	build_prod expr [] heaps
		= build_case_unit expr heaps	
	build_prod expr [cons_arg_var] heaps
		= (expr, cons_arg_var, heaps)	
	build_prod expr cons_arg_vars heaps
		#! (left_vars, right_vars) = splitAt ((length cons_arg_vars) /2) cons_arg_vars		 
		#! (expr, left_var, heaps) = build_prod expr left_vars heaps
		#! (expr, right_var, heaps) = build_prod expr right_vars heaps		
		#! (case_expr, var, heaps) = build_case_pair left_var right_var expr heaps		
		= (case_expr, var, heaps) 
	
	// build constructor applicarion expression
	build_cons_app :: !Index !DefinedSymbol !*Heaps 
		-> (!Expression, ![FreeVar], !*Heaps)
	build_cons_app cons_mod def_symbol=:{ds_arity} heaps
		#! names = ["x"  +++ toString k \\ k <- [1..ds_arity]]
		#! (var_exprs, vars, heaps) = buildVarExprs names heaps 
		#! (expr, heaps) = buildConsApp cons_mod def_symbol var_exprs heaps
	 	= (expr, vars, heaps)

	// build case expressions for PAIR, EITHER and UNIT
	build_case_unit body_expr heaps
		# unit_pat = buildPredefConsPattern PD_ConsUNIT [] body_expr predefs
		# {pds_module, pds_def} = predefs.[PD_TypeUNIT]
		# case_patterns = AlgebraicPatterns {glob_module = pds_module, glob_object = pds_def} [unit_pat]
		= build_case_expr case_patterns heaps
		
	build_case_pair var1 var2 body_expr heaps
		# pair_pat = buildPredefConsPattern PD_ConsPAIR [var1, var2] body_expr predefs	
		# {pds_module, pds_def} = predefs.[PD_TypePAIR]
		# case_patterns = AlgebraicPatterns {glob_module = pds_module, glob_object = pds_def} [pair_pat]	
		= build_case_expr case_patterns heaps
	
	build_case_either left_var left_expr right_var right_expr heaps
		# left_pat = buildPredefConsPattern PD_ConsLEFT [left_var] left_expr predefs
		# right_pat = buildPredefConsPattern PD_ConsRIGHT [right_var] right_expr predefs
		# {pds_module, pds_def} = predefs.[PD_TypeEITHER]
		# case_patterns = AlgebraicPatterns {glob_module = pds_module, glob_object = pds_def} [left_pat, right_pat]
		= build_case_expr case_patterns heaps

	// case with a variable as the selector expression
	build_case_expr case_patterns heaps
		# (var_expr, var, heaps) = buildVarExpr "c" heaps
		# (case_expr, heaps) = buildCaseExpr var_expr case_patterns heaps
		= (case_expr, var, heaps)
		

//****************************************************************************************
// build kind indexed classes 
//****************************************************************************************

buildClasses :: 
		!Int
		!NumberSet 
		!*{#CommonDefs} 
		!*{#.DclModule} 
		!*Heaps 
		!*SymbolTable 
		!*TypeDefInfos
		!*ErrorAdmin 
	->	(.{#CommonDefs}
		,.{#DclModule}
		,.Heaps
		,.SymbolTable
		,.TypeDefInfos
		,.ErrorAdmin
		)
buildClasses main_module_index used_module_numbers modules dcl_modules heaps symbol_table td_infos error
	#! (common_defs=:{com_class_defs, com_member_defs}, modules) = modules ! [main_module_index]
	#! num_classes = size com_class_defs
	#! num_members = size com_member_defs

/*
	#! (modules, (classes, members, new_num_classes, new_num_members, heaps, td_infos, error)) 
		= mapGenericCaseDefs on_gencase modules ([], [], num_classes, num_members, heaps, td_infos, error)
*/
	#! (modules, (classes, members, new_num_classes, new_num_members, heaps, td_infos, error)) 
		= build_modules 0 modules ([], [], num_classes, num_members, heaps, td_infos, error)

	// obtain common definitions again because com_gencase_defs are updated 
	#! (common_defs, modules) = modules ! [main_module_index]	
	# common_defs = 
		{ common_defs 
		& com_class_defs = arrayPlusRevList com_class_defs classes
		, com_member_defs = arrayPlusRevList com_member_defs members
		}
		
	#! (common_defs, dcl_modules, heaps, symbol_table) 
		= build_class_dictionaries common_defs dcl_modules heaps symbol_table
	
	#! modules = {modules & [main_module_index] = common_defs}	
	= (modules, dcl_modules, heaps, symbol_table, td_infos, error)  
where
	build_modules module_index modules st
		| module_index == size modules
			= (modules, st)
			#! (common_defs=:{com_gencase_defs}, modules) = modules![module_index] 
			#! (com_gencase_defs, modules, st) 
				= build_module module_index com_gencase_defs modules st 
			#! modules = 
				{ modules 
				& [module_index] = {common_defs & com_gencase_defs = com_gencase_defs }
				} 
			= build_modules (inc module_index) modules st

	build_module module_index com_gencase_defs modules st
		| inNumberSet module_index used_module_numbers
			#! com_gencase_defs = {x\\x<-:com_gencase_defs} 
			= build_module1 module_index 0 com_gencase_defs modules st
			= (com_gencase_defs, modules, st)

	build_module1 module_index index com_gencase_defs modules st
		| index == size com_gencase_defs
			= (com_gencase_defs, modules, st)
			#! (gencase, com_gencase_defs) = com_gencase_defs ! [index]
			#! (gencase, modules, st) = on_gencase module_index index gencase modules st
			#! com_gencase_defs = {com_gencase_defs & [index] = gencase} 	
			= build_module1 module_index (inc index) com_gencase_defs modules st

	on_gencase :: 
			!Index 
			!Index 
			!GenericCaseDef 
			!*Modules 
			(![ClassDef], ![MemberDef], !Index, Index, !*Heaps, !*TypeDefInfos, !*ErrorAdmin)
		->  ( !GenericCaseDef
			, !*Modules 
			, (![ClassDef], ![MemberDef], !Index, Index, !*Heaps, !*TypeDefInfos, !*ErrorAdmin)
			)
	on_gencase 
			module_index index 
			gencase=:{gc_name,gc_generic, gc_type_cons} 
			modules
			(classes, members, class_index, member_index, heaps, td_infos, error)

		#! (gen_def, modules) = modules ! [gc_generic.gi_module].com_generic_defs.[gc_generic.gi_index] 
		#! (kind, td_infos) = get_kind_of_type_cons gc_type_cons td_infos

		//#! kinds = partially_applied_kinds kind
		#! st = build_class_if_needed gen_def kind (classes, members, class_index, member_index, modules, heaps, error)	

		// build classes needed for shorthand instances
		#! (classes, members, class_index, member_index, modules, heaps, error)
			= case kind of 
				KindConst -> st
				KindArrow ks
					-> foldSt (build_class_if_needed gen_def) [KindConst:ks] st 
				
		#! gencase = { gencase & gc_kind = kind }				
		= (gencase, modules, (classes, members, class_index, member_index, heaps, td_infos, error))

	build_class_if_needed gen_def kind (classes, members, class_index, member_index, modules, heaps, error)
		#! (opt_class_info, heaps) = lookup_generic_class_info gen_def kind heaps
		= case opt_class_info of
			No 
				#! (class_def, member_def, modules, heaps, error) 
					= buildClassAndMember main_module_index class_index member_index kind gen_def modules heaps error 
				#! class_info = 
					{	gci_kind = kind
					,	gci_module = main_module_index
					,	gci_class = class_index
					,	gci_member = member_index
					}
				#! heaps = add_generic_class_info gen_def class_info heaps
				-> ([class_def:classes], [member_def:members], inc class_index, inc member_index, modules, heaps, error)
			Yes class_info	
				-> (classes, members, class_index, member_index, modules, heaps, error)
	
	partially_applied_kinds KindConst 
		= [KindConst]
	partially_applied_kinds (KindArrow kinds) 
		= do_it kinds
	where
		do_it [] = [KindConst]
		do_it all_ks=:[k:ks] = [(KindArrow all_ks) : do_it ks] 
				
	get_kind_of_type_cons :: !TypeCons !*TypeDefInfos -> (!TypeKind, !*TypeDefInfos)
	get_kind_of_type_cons (TypeConsBasic _) td_infos 
		= (KindConst, td_infos)
	get_kind_of_type_cons TypeConsArrow td_infos
		= (KindArrow [KindConst,KindConst], td_infos)
	get_kind_of_type_cons (TypeConsSymb {type_name, type_index}) td_infos
		#! ({tdi_kinds}, td_infos) = td_infos ! [type_index.glob_module,type_index.glob_object]
		= (if (isEmpty tdi_kinds) KindConst (KindArrow tdi_kinds), td_infos)
	get_kind_of_type_cons (TypeConsVar tv) td_infos
		= (KindConst, td_infos)

	lookup_generic_class_info {gen_info_ptr} kind heaps=:{hp_generic_heap}
		#! ({gen_classes}, hp_generic_heap) = readPtr gen_info_ptr hp_generic_heap
		= (lookupGenericClassInfo kind gen_classes
			, {heaps & hp_generic_heap = hp_generic_heap})

	add_generic_class_info	{gen_info_ptr} class_info heaps=:{hp_generic_heap}	
		#! (gen_info=:{gen_classes}, hp_generic_heap) = readPtr gen_info_ptr hp_generic_heap
		#! gen_classes = addGenericClassInfo class_info gen_classes
		#! hp_generic_heap = writePtr gen_info_ptr {gen_info&gen_classes=gen_classes} hp_generic_heap
		= {heaps & hp_generic_heap = hp_generic_heap}
			
	build_class_dictionaries			
			common_defs dcl_modules
			heaps=:{hp_type_heaps=hp_type_heaps=:{th_vars}, hp_var_heap}
			symbol_table 
		#! class_defs = { x \\ x <-: common_defs.com_class_defs } // make unique copy
		#  type_defs = { x \\ x <-: common_defs.com_type_defs } // make unique copy
		#  cons_defs = { x \\ x <-: common_defs.com_cons_defs } // make unique copy
		#  selector_defs = { x \\ x <-: common_defs.com_selector_defs } // make unique copy
		#  (size_type_defs,type_defs) = usize type_defs 
		#! (new_type_defs, new_selector_defs, new_cons_defs,_,type_defs,selector_defs,cons_defs,class_defs, dcl_modules, th_vars, hp_var_heap, symbol_table) =
				createClassDictionaries
					False 
					main_module_index 
					size_type_defs
					(size common_defs.com_selector_defs) 
					(size common_defs.com_cons_defs) 
					type_defs selector_defs cons_defs class_defs dcl_modules th_vars hp_var_heap symbol_table

		#! common_defs = { common_defs & 
			com_class_defs = class_defs, 
			com_type_defs = arrayPlusList type_defs new_type_defs,
			com_selector_defs = arrayPlusList selector_defs new_selector_defs,
			com_cons_defs = arrayPlusList cons_defs new_cons_defs}

		#! heaps = {heaps & hp_var_heap = hp_var_heap, hp_type_heaps = {hp_type_heaps & th_vars = th_vars}} 
		= (common_defs, dcl_modules, heaps, symbol_table)		


// limitations:
// - context restrictions on generic variables are not allowed
buildMemberType :: 
		!GenericDef 
		!TypeKind 
		!TypeVar 
		!*Modules
		!*TypeHeaps 
		!*GenericHeap
		!*ErrorAdmin
	->	( !SymbolType
		, !*Modules
		, !*TypeHeaps
		, !*GenericHeap
		, !*ErrorAdmin
		)
buildMemberType {gen_name,gen_pos,gen_type,gen_vars} kind class_var modules th gh error
	#! (kind_indexed_st, gatvs, th, error) 
		= buildKindIndexedType gen_type gen_vars kind gen_name gen_pos th error
			//---> ("buildMemberType called for", gen_name, kind, gen_type)
	#! (member_st, th, error) 
		= replace_generic_vars_with_class_var kind_indexed_st gatvs kind th error

	#! th = assertSymbolType member_st th
	#! th = assertSymbolType gen_type th
					
	= (member_st, modules, th, gh, error)
		//---> ("buildMemberType returns", gen_name, kind, member_st)
where

	replace_generic_vars_with_class_var st atvs kind th error			
		#! th = subst_gvs atvs th
			//---> ("replace_generic_vars_with_class_var called for", atvs, st)
		#! (new_st, th) = applySubstInSymbolType st th
		= (new_st, th, error)
			//---> ("replace_generic_vars_with_class_var returns", new_st)
	where
		subst_gvs atvs th=:{th_vars, th_attrs}
			#! tvs = [atv_variable \\ {atv_variable} <- atvs ]
			#! avs = [av \\ {atv_attribute=TA_Var av} <- atvs ]
			
			# th_vars = foldSt subst_tv tvs th_vars
		
/*			 			
			# th_attrs = case kind of
					KindConst -> case avs of 
						[av:avs] 	-> foldSt (subst_av av) avs th_attrs
						[] 			-> th_attrs
					_ -> th_attrs	
*/
			# th_attrs = case avs of 
				[av:avs]	-> foldSt (subst_av av) avs th_attrs
				[] 			-> th_attrs

 			= { th & th_vars = th_vars, th_attrs = th_attrs }
		
		subst_tv {tv_info_ptr} th_vars
			= writePtr tv_info_ptr (TVI_Type (TV class_var)) th_vars

		subst_av av {av_info_ptr} th_attrs
			= writePtr av_info_ptr (AVI_Attr (TA_Var av)) th_attrs
				//---> ("(1) writePtr av_info_ptr", ptrToInt av_info_ptr, av)

buildClassAndMember 
		module_index class_index member_index kind 
		gen_def=:{gen_name, gen_pos} modules heaps error
	#! (class_var, heaps) = fresh_class_var heaps
	#! (member_def, modules, heaps, error) 
		= build_class_member class_var modules heaps error	
	#! class_def = build_class class_var member_def
	= (class_def, member_def, modules, heaps, error)
		//---> ("buildClassAndMember", gen_def.gen_name, kind)
where
	fresh_class_var heaps=:{hp_type_heaps=th=:{th_vars}}
		# (tv, th_vars) = freshTypeVar (makeIdent "class_var") th_vars
		= (tv, {heaps & hp_type_heaps = { th & th_vars = th_vars }})

	class_ident = genericIdentToClassIdent gen_def.gen_name kind 
	member_ident = genericIdentToMemberIdent gen_def.gen_name kind 
	class_ds = {ds_index = class_index, ds_ident = class_ident, ds_arity = 1}

	build_class_member class_var modules heaps=:{hp_var_heap, hp_type_heaps, hp_generic_heap} error
		#! (type_ptr, hp_var_heap) = newPtr VI_Empty hp_var_heap 
		#! (tc_var_ptr, hp_var_heap) = newPtr VI_Empty hp_var_heap 
		#! type_context = 
			{	tc_class = {glob_module = module_index, glob_object=class_ds}
			,	tc_types = [ TV class_var ] 
			,	tc_var = tc_var_ptr 
			}
		#! (member_type, modules, hp_type_heaps, hp_generic_heap, error) 
			= buildMemberType gen_def kind class_var modules hp_type_heaps hp_generic_heap error
		#! member_type = { member_type & st_context = [type_context : member_type.st_context] }
		#! member_def = {
			me_symb = member_ident, 
			me_class = {glob_module = module_index, glob_object = class_index},
			me_offset = 0,
			me_type = member_type,
			me_type_ptr = type_ptr,				// empty
			me_class_vars = [class_var], 		// the same variable as in the class
			me_pos = gen_pos,
			me_priority = NoPrio
			}
				//---> ("member_type", member_type)
		= (member_def, modules, {heaps & hp_type_heaps = hp_type_heaps, hp_var_heap = hp_var_heap, hp_generic_heap = hp_generic_heap}, error)
	build_class class_var member_def=:{me_type}
		#! class_member = 
			{ ds_ident = member_ident
			, ds_index = member_index
			, ds_arity = me_type.st_arity
			}
		#! class_dictionary = 
			{ ds_ident = class_ident 
			, ds_arity = 0 
			, ds_index = NoIndex/*index in the type def table, filled in later*/ 
			}
		#! class_def = { 
			class_name = class_ident, 
			class_arity = 1,  
			class_args = [class_var],
		    class_context = [], 
		    class_pos = gen_pos, 
		    class_members = createArray 1 class_member, 
		    class_cons_vars = 0, // dotted class variables
		    class_dictionary = class_dictionary,
		    class_arg_kinds = [kind]
		    }	 
			
		= class_def	

							
//****************************************************************************************
// Convert generic cases 
//****************************************************************************************
convertGenericCases ::
		!Index					// current module
		!NumberSet				// used module numbers
		!PredefinedSymbols
		!*{#FunDef}	
		!{!Group}			
		!*{#CommonDefs}
		!*{#DclModule}
		!*TypeDefInfos
		!*Heaps
		!*ErrorAdmin
	-> 	( !IndexRange			// created instance functions
		, !*{#FunDef}			// added instance functions
		, !{!Group}				// added instance groups
		, !*{#CommonDefs}		// added instances
		, !*{#DclModule}			// updated function types
		, !*TypeDefInfos
		, !*Heaps
		, !*ErrorAdmin
		) 		
convertGenericCases 
		main_module_index used_module_numbers 
		predefs funs groups modules dcl_modules td_infos heaps error

	#! (first_fun_index, funs) = usize funs
	#! first_group_index = size groups
	#! fun_info = (first_fun_index, first_group_index, [], [])

	#! first_instance_index = size main_module_instances	
	#! instance_info = (first_instance_index, [])
	
	#! (modules1, dcl_modules, (fun_info, instance_info, funs, td_infos, heaps, error)) 
		= convert_modules 0 modules1 dcl_modules (fun_info, instance_info, funs, td_infos, heaps, error)
	
	#! (fun_index, group_index, new_funs, new_groups) = fun_info
	#! funs = arrayPlusRevList funs new_funs
	#! groups = arrayPlusRevList groups new_groups
	
	#! (instance_index, new_instances) = instance_info 
	#! com_instance_defs = arrayPlusRevList main_module_instances new_instances

	#! main_common_defs = {main_common_defs & com_instance_defs = com_instance_defs}	
	#! modules1 = {modules1 & [main_module_index] = main_common_defs}
	
	#! instance_fun_range = {ir_from=first_fun_index, ir_to=fun_index}	 
	= (instance_fun_range, funs, groups, modules1, dcl_modules, td_infos, heaps, error)
where

	(main_common_defs, modules1) = modules ! [main_module_index]
	main_module_classes = main_common_defs.com_class_defs
	main_module_members = main_common_defs.com_member_defs
	main_module_instances = main_common_defs.com_instance_defs

	convert_modules ::
			!Index
			!*{#CommonDefs}
			!*{#DclModule}
			( FunsAndGroups
			, (!Index, ![ClassInstance])
			, !*{#FunDef}
			, !*TypeDefInfos
			, !*Heaps
			, !*ErrorAdmin
			)
		-> 	(!*{#CommonDefs}
			,*{#DclModule} 
			,	( FunsAndGroups
				, (!Index, ![ClassInstance])
				, !*{#FunDef}
			 	, !*TypeDefInfos
				, !*Heaps
				, !*ErrorAdmin
				)
			)			
	convert_modules module_index modules dcl_modules st
		| module_index == size modules
			= (modules, dcl_modules, st)
			#! (common_defs=:{com_gencase_defs}, modules) = modules ! [module_index]
			#! (dcl_module=:{dcl_functions}, dcl_modules) = dcl_modules ! [module_index]
			#! (dcl_functions, modules, st) 
				= convert_module module_index com_gencase_defs {x\\x<-:dcl_functions} modules st  
			#! dcl_modules = {dcl_modules & [module_index] = {dcl_module & dcl_functions = dcl_functions}} 
			= convert_modules (inc module_index) modules dcl_modules st

	convert_module module_index com_gencase_defs dcl_functions modules st
		| inNumberSet module_index used_module_numbers		 
			#! dcl_functions = {x\\x<-:dcl_functions}
			= foldArraySt (convert_gencase module_index) 
				com_gencase_defs (dcl_functions, modules, st)
			= (dcl_functions, modules, st)

	convert_gencase :: 
			!Index
			!Index
			!GenericCaseDef
			(!*{#FunType}
			,!*Modules
			,	( FunsAndGroups
			 	, (!Index, ![ClassInstance])
			 	, !*{#FunDef}
			 	, !*TypeDefInfos
			 	, !*Heaps
			 	, !*ErrorAdmin
			 	)
			)
		-> (!*{#FunType}
			,!*Modules
			,	( FunsAndGroups
			 	, (!Index, ![ClassInstance])
			 	, !*{#FunDef}
			 	, !*TypeDefInfos
			 	, !*Heaps
			 	, !*ErrorAdmin
			 	)
			)					
	convert_gencase module_index gc_index gencase=:{gc_name, gc_type} st
		#! st = build_main_instance module_index gc_index gencase st	
		#! st = build_shorthand_instance_if_needed module_index gc_index gencase st	
		= st
			//---> ("convert gencase", gc_name, gc_type)

	build_main_instance module_index gc_index 
			gencase=:{gc_name, gc_kind, gc_generic, gc_pos, gc_type, gc_type_cons, gc_body = GCB_FunIndex fun_index} 
			(dcl_functions, modules, (fun_info, ins_info, fun_defs, td_infos, heaps, error))
		#! ({gen_classes}, modules, heaps) 
			= get_generic_info gc_generic modules heaps			
		#  (Yes class_info) 
			= lookupGenericClassInfo gc_kind gen_classes
			
		#! {class_members} 
			= main_module_classes . [class_info.gci_class] 		
		#! member_def 
			= main_module_members . [class_members.[0].ds_index]

		#! ins_type = 
			{	it_vars	= case gc_type_cons of 
					TypeConsVar tv 	-> [tv]
					_				-> []
			,	it_types = [gc_type]
			,	it_attr_vars = []
			,	it_context = []
			}

		#! (fun_type, heaps, error)
			= determine_type_of_member_instance member_def ins_type heaps error

		#! (dcl_functions, heaps) 
			= update_dcl_function fun_index gencase fun_type dcl_functions heaps

		#! (fun_info, fun_defs, td_infos, modules, heaps, error) 
				= update_icl_function_if_needed 
						module_index 
						fun_index gencase fun_type 
						fun_info fun_defs td_infos modules heaps error

		#! (fun_info, ins_info, heaps)
			= build_instance_and_member module_index class_info.gci_class gencase fun_type ins_type fun_info ins_info heaps  
		
		= (dcl_functions, modules, (fun_info, ins_info, fun_defs, td_infos, heaps, error))

	build_shorthand_instance_if_needed module_index gc_index gencase=:{gc_kind=KindConst} st
		= st
	build_shorthand_instance_if_needed 
			module_index gc_index 
			gencase=:{gc_name, gc_generic, gc_kind=KindArrow arg_kinds, gc_type} 
			(dcl_functions, modules, (fun_info, ins_info, fun_defs, td_infos, heaps, error))

		#! (star_class_info, (modules, heaps)) 
			= get_class_for_kind gc_generic KindConst (modules, heaps)

		#! (arg_class_infos, (modules, heaps)) 
			= mapSt (get_class_for_kind gc_generic) arg_kinds (modules, heaps)

		#! {class_members} 
			= main_module_classes . [star_class_info.gci_class] 		
		#! member_def 
			= main_module_members . [class_members.[0].ds_index]

		#! (ins_type, heaps) 
			= build_instance_type gc_type arg_class_infos heaps

		#! (fun_type, heaps, error)
			= determine_type_of_member_instance member_def ins_type heaps error
		
		#! (memfun_ds, fun_info, heaps) 
			= build_shorthand_instance_member module_index gencase fun_type arg_class_infos fun_info heaps
		
		#! ins_info 
			= build_class_instance star_class_info.gci_class gencase memfun_ds ins_type ins_info
				
		= (dcl_functions, modules, (fun_info, ins_info, fun_defs, td_infos, heaps, error))
	where
		build_instance_type type class_infos heaps=:{hp_type_heaps=th=:{th_vars},hp_var_heap}
			#! arity = length class_infos
			#! type_var_names = [makeIdent ("a" +++ toString i) \\ i <- [1 .. arity]]
			#! (type_vars, th_vars) = mapSt freshTypeVar type_var_names th_vars 
			#! type_var_types = [TV tv \\ tv <- type_vars] 	
			#! new_type_args = [makeAType t TA_Multi \\ t <- type_var_types]
			
			#! type = fill_type_args type new_type_args	
			
			#! (contexts, hp_var_heap) 
				= zipWithSt build_context class_infos type_vars hp_var_heap
			
			#! ins_type = 
				{	it_vars	= type_vars
				,	it_types = [type]
				,	it_attr_vars = []
				,	it_context = contexts
				}
											 
			= (ins_type, {heaps & hp_type_heaps = {th & th_vars = th_vars}, hp_var_heap = hp_var_heap})
				//---> ("instance type for shorthand instance", gc_name, gc_type, ins_type)
		where
			fill_type_args (TA type_symb_ident=:{type_arity} type_args) new_type_args
				#! type_arity = type_arity + length new_type_args 
				#! type_args = type_args ++ new_type_args
				= TA {type_symb_ident & type_arity = type_arity} type_args 
			fill_type_args TArrow [arg_type, res_type]
				= arg_type --> res_type
			fill_type_args (TArrow1 arg_type) [res_type]
				= arg_type --> res_type	 
			fill_type_args type args
				= abort ("fill_type_args\n"---> ("fill_type_args", type, args)) 

			build_context {gci_class, gci_module, gci_kind} tv hp_var_heap
				# (var_info_ptr, hp_var_heap) = newPtr VI_Empty hp_var_heap			
				# type_context =		
					{	tc_class = 
							{ glob_module=gci_module // the same as icl module
							, glob_object =
								{ ds_ident = genericIdentToClassIdent gc_name gci_kind
								, ds_index = gci_class
								, ds_arity = 1
								}
							}
					,	tc_types = [TV tv]
					,	tc_var	 = var_info_ptr
					}
				= (type_context, hp_var_heap)	

	get_generic_info {gi_module, gi_index} modules heaps=:{hp_generic_heap}
		#! ({gen_info_ptr}, modules) 
			= modules ! [gi_module] . com_generic_defs . [gi_index]
		#! (gen_info, hp_generic_heap) = readPtr gen_info_ptr hp_generic_heap	
		= (gen_info, modules, {heaps & hp_generic_heap = hp_generic_heap})

	get_class_for_kind generic_gi kind (modules, heaps)
		#! ({gen_classes}, modules, heaps) = get_generic_info generic_gi modules heaps
		# (Yes class_info) = lookupGenericClassInfo kind gen_classes
		= (class_info, (modules, heaps))	


	determine_type_of_member_instance :: !MemberDef !InstanceType !*Heaps !*ErrorAdmin
		-> (!SymbolType, !*Heaps, !*ErrorAdmin)
	determine_type_of_member_instance {me_type, me_class_vars} ins_type heaps=:{hp_type_heaps, hp_var_heap} error
		#! (symbol_type, _, hp_type_heaps, _, error) 
			= determineTypeOfMemberInstance me_type me_class_vars ins_type SP_None hp_type_heaps No error
		#! (st_context, hp_var_heap) = initializeContextVariables symbol_type.st_context hp_var_heap
		#! hp_type_heaps = clearSymbolType me_type hp_type_heaps
		#! symbol_type = {symbol_type & st_context = st_context}
		#! heaps = {heaps & hp_type_heaps = hp_type_heaps, hp_var_heap = hp_var_heap}
		= (symbol_type, heaps, error)
			//---> ("determine_type_of_member_instance", ins_type, symbol_type) 

	update_dcl_function :: !Index !GenericCaseDef !SymbolType !*{#FunType} !*Heaps
		-> (!*{#FunType}, !*Heaps)
	update_dcl_function fun_index {gc_name, gc_type_cons} symbol_type dcl_functions heaps 
		| fun_index < size dcl_functions
			#! (symbol_type, heaps) = fresh_symbol_type symbol_type heaps			
			#! (fun, dcl_functions) = dcl_functions ! [fun_index]
			#! fun = 
				{ fun 
				& ft_symb = genericIdentToFunIdent gc_name gc_type_cons
				, ft_type = symbol_type
				}
			#! dcl_functions = { dcl_functions & [fun_index] = fun}
			= (dcl_functions, heaps)
				//---> ("update dcl function", fun.ft_symb, fun_index, symbol_type)  
			= (dcl_functions, heaps)
				//---> ("update dcl function: not in the dcl module", fun_index)  

	update_icl_function_if_needed module_index fun_index gencase fun_type fun_info fun_defs td_infos modules heaps error
		| module_index == main_module_index  // current module
			#! (fi, gi, fs, gs) = fun_info
			#! (gi, gs, fun_defs, td_infos, modules, heaps, error) 
				= update_icl_function fun_index gencase fun_type gi gs fun_defs td_infos modules heaps error
			= ((fi, gi, fs, gs), fun_defs, td_infos, modules, heaps, error)
			= (fun_info, fun_defs, td_infos, modules, heaps, error)
			
	update_icl_function :: 
			!Index !GenericCaseDef !SymbolType 
			!Index ![Group] !*{#FunDef} !*TypeDefInfos !*{#CommonDefs} !*Heaps !*ErrorAdmin 
		-> (!Index, ![Group], !*{#FunDef}, !*TypeDefInfos, !*{#CommonDefs}, !*Heaps, !*ErrorAdmin)
	update_icl_function fun_index gencase=:{gc_name, gc_type_cons, gc_pos} st group_index groups fun_defs td_infos modules heaps error
		#! (st, heaps) = fresh_symbol_type st heaps
		#! (fun=:{fun_body, fun_arity}, fun_defs) = fun_defs ! [fun_index] 		
		#! fun_ident = genericIdentToFunIdent gc_name gc_type_cons
		= case fun_body of 
			TransformedBody tb	// user defined case			
				| fun_arity <> st.st_arity						
					# error = reportError gc_name gc_pos 
						("incorrect arity: " +++ toString st.st_arity +++ " expected") error
					-> (group_index, groups, fun_defs, td_infos, modules, heaps, error)	
				#! fun = 
					{ fun 
					& fun_symb = fun_ident 
					, fun_type = Yes st
					, fun_body = fun_body
					}
				#! fun_defs = { fun_defs & [fun_index] = fun }		
				-> (group_index, groups, fun_defs, td_infos, modules, heaps, error)	
					//---> ("update_icl_function, TransformedBody", fun.fun_symb, fun_index, st)
						
			GeneratedBody		// derived case
				#! (TransformedBody {tb_args, tb_rhs}, td_infos, modules, heaps, error)  
						= buildGenericCaseBody main_module_index gencase st predefs td_infos modules heaps error
					//---> ("call buildGenericCaseBody\n")
				#! fun = makeFunction fun_ident fun_index group_index tb_args tb_rhs (Yes st) main_module_index gc_pos
				#! fun_defs = { fun_defs & [fun_index] = fun }
				
				# group = {group_members=[fun_index]}
						
				-> (inc group_index, [group:groups], fun_defs, td_infos, modules, heaps, error)
					//---> ("update_icl_function, GeneratedBody", fun.fun_symb, fun_index, st)
			_ -> abort "update_icl_function: generic case body\n"
	
	// build wrapping instance for the generic case function
	build_instance_and_member :: !Index !Index !GenericCaseDef !SymbolType !InstanceType !FunsAndGroups (!Index, ![ClassInstance]) !*Heaps
		-> (!FunsAndGroups, (!Index, ![ClassInstance]), !*Heaps)
	build_instance_and_member module_index class_index gencase symbol_type ins_type fun_info ins_info heaps
		#! (memfun_ds, fun_info, heaps) 
			= build_instance_member module_index gencase symbol_type fun_info heaps
		#! ins_info = build_class_instance class_index gencase memfun_ds ins_type ins_info
		= (fun_info, ins_info, heaps)
	
	// Creates a function that just calls the generic case function
	// It is needed because the instance member must be in the same
	// module as the instance itself
	build_instance_member module_index gencase st fun_info heaps
	
		# {gc_name, gc_pos, gc_type_cons, gc_kind, gc_body=GCB_FunIndex fun_index} = gencase
		#! arg_var_names = ["x" +++ toString i \\ i <- [1..st.st_arity]]
		#! (arg_var_exprs, arg_vars, heaps) = buildVarExprs arg_var_names heaps
	
		#! (expr_info_ptr, hp_expression_heap) = newPtr EI_Empty heaps.hp_expression_heap
		#! heaps = {heaps & hp_expression_heap = hp_expression_heap}
		#! fun_name = genericIdentToFunIdent gc_name gc_type_cons
		#! expr = App 
			{ app_symb = 
				{ symb_name=fun_name
				, symb_kind=SK_Function {glob_module=module_index, glob_object=fun_index}
				}
			, app_args = arg_var_exprs
			, app_info_ptr = expr_info_ptr
			}
	
		#! (st, heaps) = fresh_symbol_type st heaps
	
		#! memfun_name = genericIdentToMemberIdent gc_name gc_kind
		#! (fun_ds, fun_info) 
			= buildFunAndGroup memfun_name arg_vars expr (Yes st) main_module_index gc_pos fun_info
		= (fun_ds, fun_info, heaps)
	
	build_shorthand_instance_member module_index gencase=:{gc_generic, gc_name, gc_kind, gc_pos} st class_infos fun_info heaps
		#! arg_var_names = ["x" +++ toString i \\ i <- [1..st.st_arity]]
		#! (arg_var_exprs, arg_vars, heaps) = buildVarExprs arg_var_names heaps
	
		#! (expr_info_ptr, hp_expression_heap) = newPtr EI_Empty heaps.hp_expression_heap
		#! heaps = {heaps & hp_expression_heap = hp_expression_heap}
		#! fun_name = genericIdentToMemberIdent gc_name KindConst

		# (gen_exprs, heaps) = mapSt (build_generic_app gc_generic gc_name) class_infos heaps

		# (body_expr, heaps) 
			= buildGenericApp gc_generic.gi_module gc_generic.gi_index 
				gc_name gc_kind (gen_exprs ++ arg_var_exprs) heaps

		#! (st, heaps) = fresh_symbol_type st heaps
	
		#! (fun_ds, fun_info) 
			= buildFunAndGroup fun_name arg_vars body_expr (Yes st) main_module_index gc_pos fun_info

		= (fun_ds, fun_info, heaps)		
			//---> ("shorthand instance body", body_expr)
	where
		build_generic_app {gi_module, gi_index} gc_name {gci_kind} heaps
			= buildGenericApp gi_module gi_index gc_name gci_kind [] heaps	
	
	build_class_instance class_index gencase member_fun_ds ins_type (ins_index, instances) 
		
		# {gc_pos, gc_name, gc_kind} = gencase
		
		#! class_name = genericIdentToClassIdent gc_name gc_kind		
		#! class_ds = {ds_index = class_index, ds_arity=1, ds_ident=class_name}
		#! ins = 
		 	{	ins_class 	= {glob_module=main_module_index, glob_object=class_ds}
			,	ins_ident 	= class_name
			,	ins_type 	= ins_type
			,	ins_members	= {member_fun_ds}
			,	ins_specials = SP_None
			,	ins_pos		= gc_pos
			}
		
		= (inc ins_index, [ins:instances])
	
	fresh_symbol_type :: !SymbolType !*Heaps -> (!SymbolType, !*Heaps)	
	fresh_symbol_type st heaps=:{hp_type_heaps}
		# (fresh_st, hp_type_heaps) = freshSymbolType st hp_type_heaps
		= (fresh_st, {heaps & hp_type_heaps = hp_type_heaps})	
			//---> ("fresh_symbol_type")
		
buildGenericCaseBody :: 
		!Index
		!GenericCaseDef
		!SymbolType
		!PredefinedSymbols
		!*TypeDefInfos
		!*{#CommonDefs} 
		!*Heaps 
		!*ErrorAdmin 
	-> 	( !FunctionBody
		, !*TypeDefInfos
		, !*{#CommonDefs}
		, !*Heaps
		, !*ErrorAdmin
		)
buildGenericCaseBody main_module_index {gc_name,gc_pos, gc_generic, gc_type_cons=TypeConsSymb {type_index}} st predefs td_infos modules heaps error

	// get all the data we need
	#! (gen_def=:{gen_vars, gen_type, gen_bimap}, modules) 	
		= modules ! [gc_generic.gi_module].com_generic_defs.[gc_generic.gi_index] 
	#! (td_info=:{tdi_gen_rep}, td_infos)
		= td_infos ! [type_index.glob_module, type_index.glob_object]
	# ({gtr_iso, gtr_type}) = case tdi_gen_rep of
		Yes x -> x
		No -> abort "no generic representation\n"

	#! (type_def=:{td_args}, modules) 
		= modules ! [type_index.glob_module].com_type_defs.[type_index.glob_object]
	
	#! original_arity 	= gen_type.st_arity 			// arity of generic type
	#! generated_arity 	= st.st_arity - original_arity	// number of added arguments (arity of the kind)	

	// generate variable names and exprs
	#! generated_arg_names = [ "f" +++ toString n \\ n <- [1 .. generated_arity]]
	#! (generated_arg_exprs, generated_arg_vars, heaps) = buildVarExprs generated_arg_names heaps	
	#! original_arg_names = [ "x" +++ toString n \\ n <- [1 .. original_arity]]  
	#! (original_arg_exprs, original_arg_vars, heaps) = buildVarExprs original_arg_names heaps	
	#! arg_vars = generated_arg_vars ++ original_arg_vars

	// create adaptor
	#! (iso_exprs, heaps) 
		= unfoldnSt (buildFunApp main_module_index gtr_iso []) (length gen_vars) heaps	
	#! (bimap_id_exprs, heaps) 
		= unfoldnSt (buildPredefFunApp PD_bimapId [] predefs) (length (gen_type.st_vars -- gen_vars)) heaps 

	//#! (bimap_expr, heaps) 
	//	= buildFunApp main_module_index gen_bimap iso_exprs heaps
	#! spec_env = 
		[(tv,expr)\\tv <- gen_vars & expr <- iso_exprs]	
		++
		[(tv,expr)\\tv <- gen_type.st_vars -- gen_vars & expr <- bimap_id_exprs]
	#! curried_gen_type = curry_symbol_type gen_type
	#! {pds_module = bimap_module, pds_def=bimap_index} = predefs.[PD_GenericBimap]
	
	#! (bimap_expr, (td_infos, heaps, error)) 
		= buildSpecializedExpr1 
			bimap_module bimap_index 
			curried_gen_type spec_env
			gc_name gc_pos 
			(td_infos, heaps, error)	
					
	#! adaptor_expr = buildRecordSelectionExpr bimap_expr PD_map_from predefs	

	// create expression for the generic representation
	#! spec_env = [(atv_variable, expr) \\ {atv_variable} <- td_args & expr <- generated_arg_exprs] 
	#! (specialized_expr, (td_infos, heaps, error)) 
		= buildSpecializedExpr1 
			gc_generic.gi_module gc_generic.gi_index 
			gtr_type spec_env
			gc_name gc_pos 
			(td_infos, heaps, error)

	// create the body expr
	#! body_expr = if (isEmpty original_arg_exprs)
		(adaptor_expr @ [specialized_expr]) 
		((adaptor_expr @ [specialized_expr]) @ original_arg_exprs)
  
	= (TransformedBody {tb_args=arg_vars, tb_rhs=body_expr}, td_infos, modules, heaps, error)	
		//---> (" buildGenericCaseBody", body_expr)
where
	curry_symbol_type {st_args, st_result}
		= foldr (\x y -> makeAType (x --> y) TA_Multi) st_result st_args 	

//buildGenericCaseBody main_module_index {gc_name,gc_pos, gc_generic, gc_type_cons=TypeConsSymb {type_index}} st predefs td_infos modules heaps error
buildGenericCaseBody main_module_index {gc_name,gc_pos} st predefs td_infos modules heaps error
	# error = reportError gc_name gc_pos "cannot specialize to this type" error
	= (TransformedBody {tb_args=[], tb_rhs=EE}, td_infos, modules, heaps, error)
			 							 
//****************************************************************************************
//  specialization
//****************************************************************************************

buildSpecializedExpr1 ::
		!Index					// generic module
		!Index					// generic index
		!AType					// type to specialize to
		![(TypeVar, Expression)] // specialization environment
		!Ident					// generic/generic case
		!Position				// of generic case
		(!*TypeDefInfos, !*Heaps, !*ErrorAdmin)
	->  ( !Expression
		, !(!*TypeDefInfos, !*Heaps, !*ErrorAdmin)
		)
buildSpecializedExpr1 gen_module gen_index atype spec_env ident pos (td_infos, heaps, error)

	#! heaps = set_tvs spec_env heaps
	#! (expr, (td_infos, heaps, error)) 
		= buildSpecializedExpr gen_module gen_index atype ident pos (td_infos, heaps, error)

	#! heaps = clear_tvs spec_env heaps
	= (expr, (td_infos, heaps, error))
where
	set_tvs spec_env heaps=:{hp_type_heaps=hp_type_heaps=:{th_vars}}
		#! th_vars = foldSt write_tv spec_env th_vars
			with write_tv ({tv_info_ptr}, expr) th_vars
					= writePtr tv_info_ptr (TVI_Expr expr) th_vars		
		= {heaps & hp_type_heaps = {hp_type_heaps & th_vars = th_vars }}

	clear_tvs spec_env heaps=:{hp_type_heaps=hp_type_heaps=:{th_vars}}
		#! th_vars = foldSt write_tv spec_env th_vars
			with write_tv ({tv_info_ptr}, _) th_vars
					= writePtr tv_info_ptr TVI_Empty th_vars		
		= {heaps & hp_type_heaps = {hp_type_heaps & th_vars = th_vars }}

// generates an expression that corresponds to a type
buildSpecializedExpr ::
		!Index					// generic module index
		!Index 					// generic index
		!AType					// type to specialize to
								// tv_info_ptr of type variables must contain expressions
								// corresponding to the type variables 
		!Ident					// for error reporting
		!Position				// for error reporting
		!(!*TypeDefInfos, !*Heaps, !*ErrorAdmin)
	->  ( !Expression			// generated expression
		, !(!*TypeDefInfos, !*Heaps, !*ErrorAdmin)
		)
buildSpecializedExpr gen_module gen_index type gen_name pos gs 
	= spec_atype type gs
where
	spec_atype {at_type} gs = spec_type at_type gs 

	spec_atypes [] gs = ([], gs)
	spec_atypes [type:types]  gs
		# (expr, gs) = spec_atype type gs 
		# (exprs, gs) = spec_atypes types gs 
		= ([expr:exprs], gs)

	spec_type :: !Type !(!*TypeDefInfos, !*Heaps, !*ErrorAdmin)
		-> !(Expression, !(!*TypeDefInfos, !*Heaps, !*ErrorAdmin))
	spec_type (TA {type_index, type_name} args) st
		# (arg_exprs, st) = spec_atypes args st
		# (kind, st) = get_kind type_index st 
		= build_generic_app kind arg_exprs st  
	spec_type (TAS {type_index, type_name} args _) st
		# (arg_exprs, st) = spec_atypes args st
		# (kind, st) = get_kind type_index st 
		= build_generic_app kind arg_exprs st  
	spec_type (arg_type --> res_type) st
		#! (arg_expr, st) = spec_atype arg_type st
		#! (res_expr, st) = spec_atype res_type st
		= build_generic_app (KindArrow [KindConst, KindConst]) [arg_expr, res_expr] st
	spec_type ((CV type_var) :@: args) gs 
		#! (expr, gs) = spec_type_var type_var gs
		#! (exprs, gs) = spec_atypes args gs
		= (expr @ exprs, gs)	
	spec_type (TB basic_type) st
		= build_generic_app KindConst [] st
	spec_type (TFA atvs type) (td_infos, heaps, error) 
		#! error = reportError gen_name pos "cannot specialize to forall types" error
		= (EE, (td_infos, heaps, error))
	spec_type (TV type_var) gs  = spec_type_var type_var gs
	//spec_type (GTV type_var) gs = spec_type_var type_var gs
	//spec_type (TQV type_var) gs = spec_type_var type_var gs
	//spec_type (TLifted type_var) gs = spec_type_var type_var gs
	spec_type _ (td_infos, heaps, error)
		#! error = reportError gen_name pos "cannot specialize to this type" error
		= (EE, (td_infos, heaps, error))
	
	spec_type_var tv=:{tv_info_ptr} (td_infos, heaps=:{hp_type_heaps=th=:{th_vars}}, error)		
		#! (TVI_Expr expr, th_vars) = readPtr tv_info_ptr th_vars
		= (expr, (td_infos, {heaps & hp_type_heaps = {th & th_vars = th_vars}}, error))

	build_generic_app kind arg_exprs (td_infos, heaps, error)
		# (expr, heaps) 
			= buildGenericApp gen_module gen_index gen_name kind arg_exprs heaps 
		= (expr, (td_infos, heaps, error))

	get_kind {glob_module, glob_object} (td_infos, heaps, error)
		# (td_info, td_infos) = td_infos ! [glob_module, glob_object]
		= (make_kind td_info.tdi_kinds, (td_infos, heaps, error))
	where	
		make_kind [] = KindConst
		make_kind ks = KindArrow ks
		
//****************************************************************************************
//	kind indexing of generic types
//****************************************************************************************

// kind indexing:
// t_* a1 ... an 			= t a1 ... an 
// t_{k->l} a1 ... an		= forall b1...bn.(t_k b1 ... bn) -> (t_l (a1 b1) ... (an bn)) 
buildKindIndexedType :: 
		!SymbolType			// symbol type to kind-index
		![TypeVar]			// generic type variables
		!TypeKind			// kind index
		!Ident				// name for debugging
		!Position 			// position for debugging
		!*TypeHeaps			// type heaps
		!*ErrorAdmin		
	-> 	( !SymbolType		// instantiated type
		, ![ATypeVar]		// fresh generic type variables
		, !*TypeHeaps		// type heaps
		, !*ErrorAdmin	
		)
buildKindIndexedType st gtvs kind ident pos th error
	
	#! th = clearSymbolType st th
		//---> ("buildKindIndexedType called for", kind, gtvs, st)			 
	#! (fresh_st, fresh_gtvs, th) = fresh_generic_type st gtvs th	

	#! (gatvs, th) = collectAttrsOfTypeVarsInSymbolType fresh_gtvs fresh_st th

	#! (kind_indexed_st, _, th, error) = build_symbol_type fresh_st gatvs kind 1 th error	
	 	 
	#! th = clearSymbolType kind_indexed_st th
	#! th = clearSymbolType st th				// paranoja
	= (kind_indexed_st, gatvs, th, error)
		//---> ("buildKindIndexedType returns", kind_indexed_st)			 
where

	fresh_generic_type st gtvs th
		# (fresh_st, th) = freshSymbolType st th
		# fresh_gtvs = take (length gtvs) fresh_st.st_vars		
		= (fresh_st, fresh_gtvs, th)
			//---> ("fresh_generic_type", fresh_gtvs, fresh_st)

	build_symbol_type :: 
			 !SymbolType 	// generic type, 
			 ![ATypeVar]		// attributed generic variables
			 !TypeKind 		// kind to specialize to 
			 !Int 			// current order (in the sense of the order of the kind)
			 !*TypeHeaps
			 !*ErrorAdmin	
		-> ( !SymbolType	// new generic type
			, ![ATypeVar]	// fresh copies of generic variables created for the 
							// generic arguments
			, !*TypeHeaps
			, !*ErrorAdmin
			)
	build_symbol_type st gatvs KindConst order th error	
		= (st, [], th, error)
	build_symbol_type st gatvs (KindArrow kinds) order th error
		| order > 2
				//---> ("build_symbol_type called for", (KindArrow kinds), gatvs, st)
			# error = reportError ident pos "kinds of order higher then 2 are not supported" error
			= (st, [], th, error)
		
		# (arg_sts, arg_gatvss, th, error) 
			= build_args st gatvs order kinds th error 

		# (body_st, th) 
			= build_body st gatvs (transpose arg_gatvss) th 

		# num_added_args = length kinds
		# new_st = 
			{ st_vars = removeDup (
					foldr (++) body_st.st_vars [st_vars \\ {st_vars}<-arg_sts])
			, st_attr_vars = removeDup (
					foldr (++) body_st.st_attr_vars [st_attr_vars \\ {st_attr_vars}<-arg_sts])
			, st_args = [st_result \\ {st_result}<-arg_sts] ++ body_st.st_args
			, st_result = body_st.st_result 
			, st_arity = body_st.st_arity + num_added_args
			, st_context = removeDup(
				foldr (++) body_st.st_context [st_context \\ {st_context} <- arg_sts])
			, st_attr_env = removeDup(
				foldr (++) body_st.st_attr_env [st_attr_env \\ {st_attr_env} <- arg_sts])
			, st_args_strictness = insert_n_lazy_values_at_beginning num_added_args body_st.st_args_strictness	 
			}
	
		= (new_st, flatten arg_gatvss, th, error)
			//---> ("build_symbol_type returns", arg_gatvss, st)

	build_args st gatvs order kinds th error
		# (arg_sts_and_gatvss, (_,th,error)) 
			= mapSt (build_arg st gatvs order) kinds (1,th,error)
		# (arg_sts, arg_gatvss) = unzip arg_sts_and_gatvss
		= (arg_sts, arg_gatvss, th, error)

	build_arg :: 
			!SymbolType 		// current part of the generic type
			![ATypeVar]			// generic type variables with their attrs
			!Int 				// order
			!TypeKind			// kind corrseponding to the arg
			( !Int				// the argument number
			, !*TypeHeaps
			, !*ErrorAdmin
			)				
		->  ( (!SymbolType, [ATypeVar]) // fresh symbol type and generic variables 
			, 	( !Int			// incremented argument number
				, !*TypeHeaps
				, !*ErrorAdmin
				)
			)
	build_arg st gatvs order kind (arg_num, th, error)		
		#! th = clearSymbolType st th
			//---> ("build_arg called for", arg_num, kind, gatvs, st)
		#! (fresh_gatvs, th) = mapSt subst_gatv gatvs th 
		#! (new_st, th) = applySubstInSymbolType st th
		
		#! (new_st, forall_atvs, th, error) 
			= build_symbol_type new_st fresh_gatvs kind (inc order) th error	
		#! (curry_st, th)	
			= curryGenericArgType1 new_st ("cur" +++ toString order +++ postfix) th 	
		
		#! curry_st = adjust_forall curry_st forall_atvs
				
		= ((curry_st, fresh_gatvs), (inc arg_num, th, error))
			//---> ("build_arg returns", fresh_gatvs, curry_st)		
	where
		postfix = toString arg_num
		 
		subst_gatv atv=:{atv_attribute, atv_variable} th=:{th_attrs, th_vars}			
			# (tv, th_vars) = subst_gtv atv_variable th_vars 
			# (attr, th_attrs) = subst_attr atv_attribute th_attrs 			
			=	( {atv & atv_variable = tv, atv_attribute = attr}
			 	, {th & th_vars = th_vars, th_attrs = th_attrs}
			 	)	
			
		// generic type var is replaced with a fresh one
		subst_gtv {tv_info_ptr, tv_name} th_vars 
			# (tv, th_vars) = freshTypeVar (postfixIdent tv_name postfix) th_vars	
			= (tv, writePtr tv_info_ptr (TVI_Type (TV tv)) th_vars)
		
		subst_attr (TA_Var {av_name, av_info_ptr}) th_attrs 
			# (av, th_attrs) = freshAttrVar (postfixIdent av_name postfix) th_attrs
			= (TA_Var av, writePtr av_info_ptr (AVI_Attr (TA_Var av)) th_attrs)
				//---> ("(2) writePtr av_info_ptr", ptrToInt av_info_ptr, av)
		subst_attr TA_Multi th = (TA_Multi, th)
		subst_attr TA_Unique th = (TA_Unique, th)

		adjust_forall curry_st [] = curry_st
		adjust_forall curry_st=:{st_result} forall_atvs 
			#! st_result = {st_result & at_type = TFA forall_atvs st_result.at_type}
		 	= 	{ curry_st 
				& st_result = st_result
				, st_attr_vars 
					= curry_st.st_attr_vars -- [av \\ {atv_attribute=TA_Var av} <- forall_atvs]
				, st_vars 
					= curry_st.st_vars -- [atv_variable \\ {atv_variable} <- forall_atvs]
				} 
				//---> ("adjust forall", curry_st.st_vars, forall_atvs, curry_st.st_vars -- [atv_variable \\ {atv_variable} <- forall_atvs])								

	build_body :: 
			!SymbolType 
			![ATypeVar]
			![[ATypeVar]]
			!*TypeHeaps
		->	(!SymbolType
			, !*TypeHeaps
			)
	build_body st gatvs arg_gatvss  th
		# th = clearSymbolType st th
		# th = fold2St subst_gatv gatvs arg_gatvss th
		= applySubstInSymbolType st th 
	where
		subst_gatv gatv=:{atv_variable} arg_gatvs th=:{th_vars}
			#! type_args = [ makeAType (TV atv_variable) atv_attribute 
							\\ {atv_variable, atv_attribute} <- arg_gatvs]
			#! type = (CV atv_variable) :@: type_args
			#! th_vars = writePtr atv_variable.tv_info_ptr (TVI_Type type) th_vars
			= {th & th_vars = th_vars}	
		
reportError name pos msg error=:{ea_file} 
	//= checkErrorWithIdentPos (newPosition name pos) msg error
	# ea_file = ea_file <<< "Error " <<< (newPosition name pos) <<< ":" <<< msg <<< '\n'
	= { error & ea_file = ea_file , ea_ok = False }

reportWarning name pos msg error=:{ea_file}
	# ea_file = ea_file <<< "Warning " <<< (newPosition name pos) <<< ":" <<< msg <<< '\n'
	= { error & ea_file = ea_file }
	
//****************************************************************************************
//	Type Helpers
//****************************************************************************************
makeAType :: !Type !TypeAttribute -> !AType
makeAType type attr = {	at_attribute = attr, at_type = type }

makeATypeVar :: !TypeVar !TypeAttribute -> !ATypeVar
makeATypeVar tv attr = {atv_variable = tv, atv_attribute = attr}

//----------------------------------------------------------------------------------------
// folding of a AType, depth first 
//----------------------------------------------------------------------------------------

class foldType t :: (Type  .st -> .st) (AType  .st -> .st) t .st -> .st

instance foldType [a] | foldType a where
	foldType on_type on_atype types st 
		= foldSt (foldType on_type on_atype) types st

instance foldType (a,b) | foldType a & foldType b where
	foldType on_type on_atype (x,y) st 
		= foldType on_type on_atype y (foldType on_type on_atype x st)

instance foldType Type where
	foldType on_type on_atype type st
		# st = fold_type type st
		= on_type type st 
	where
		fold_type (TA type_symb args) st = foldType on_type on_atype args st
		fold_type (TAS type_symb args _) st = foldType on_type on_atype args st
		fold_type (l --> r) st = foldType on_type on_atype (l,r) st
		fold_type (TArrow) st = st
		fold_type (TArrow1 t) st = foldType on_type on_atype t st
		fold_type (_ :@: args) st = foldType on_type on_atype args st
		fold_type (TB _) st = st
		fold_type (TFA tvs type) st = foldType on_type on_atype type st
		fold_type (GTV _) st = st
		fold_type (TV _) st = st		
		fold_type t st = abort "foldType: does not match\n" ---> ("type", t)

instance foldType AType where
	foldType on_type on_atype atype=:{at_type} st 
		# st = foldType on_type on_atype at_type st
		= on_atype atype st 

instance foldType TypeContext where
	foldType on_type on_atype {tc_types} st
		= foldType on_type on_atype tc_types st 

//----------------------------------------------------------------------------------------
// mapping of a AType, depth first 
//----------------------------------------------------------------------------------------
class mapTypeSt type :: 
1805
1806
1807
1808
1809
	(Type  -> u:(.st -> u:(Type, .st))) 			// called on each type before recursion
	(AType -> u:(.st -> u:(AType, .st))) 		// called on each attributed type before recursion
	(Type  -> u:(.st -> u:(Type, .st))) 			// called on each type after recursion
	(AType -> u:(.st -> u:(AType, .st))) 		// called on each attributed type after recursion	
	type .st -> u:(type, .st)
1810
1811

mapTypeBeforeSt :: 
1812
1813
1814
	(Type  -> u:(.st -> u:(Type, .st))) 			// called on each type before recursion
	(AType  -> u:(.st -> u:(AType, .st))) 		// called on each attributed type before recursion
	type .st -> u:(type, .st) | mapTypeSt type
1815
1816
1817
1818
mapTypeBeforeSt on_type_before on_atype_before type st
	= mapTypeSt on_type_before on_atype_before idSt idSt type st
	
mapTypeAfterSt :: 
1819
1820
1821
	(Type  -> u:(.st -> u:(Type, .st))) 			// called on each type after recursion
	(AType  -> u:(.st -> u:(AType, .st))) 		// called on each attributed type after recursion
	type .st -> u:(type, .st) | mapTypeSt type
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
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443