summaryrefslogtreecommitdiff
path: root/gcc/melt/warmelt-macro.melt
blob: 6eead1ed22f8cc26e00da09b1011b35d405f1a08 (plain)
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
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
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
;; file warmelt-macro.melt -*- Lisp -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(comment "***
    Copyright 2008 - 2014  Free Software Foundation, Inc.
    Contributed by Basile Starynkevitch <basile@starynkevitch.net>

    This file is part of GCC.

    GCC is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3, or (at your option)
    any later version.

    GCC is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with GCC; see the file COPYING3.  If not see
    <http://www.gnu.org/licenses/>.
***")

;; the copyright notice above apply both to warmelt-macro.melt and 
;; to the generated files warmelt-macro*.c



;; This MELT module is GPL compatible since it is GPLv3+ licensed.
(module_is_gpl_compatible "GPLv3+")

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;    This file is part of a bootstrapping compiler for the MELT lisp
;;    dialect, compiler which should be able to compile itself (into
;;    generated C file[s])
;;    ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;




;;****************************************************************
;; Variadic diagnostic support should be here, not in warmelt-base.melt

;;;;;;; variadic diagnostics
(defvar diagv_gimple)
(defvar diagv_gimple_seq)
(defvar diagv_tree)
(defvar diagv_basic_block)
(defvar diagv_edge)

(defun register_diag_gimple (c)
  :doc #{Register a closure to handle @code{:gimple} stuff in diagnostic messages.}#
  (if (is_closure c)
      (setq diagv_gimple c)))

(defun register_diag_gimple_seq (c)
  :doc #{Register a closure to handle @code{:gimple_seq} stuff in diagnostic messages.}#
  (if (is_closure c)
      (setq diagv_gimple_seq c)))

(defun register_diag_tree (c)
  :doc #{Register a closure to handle @code{:tree} stuff in diagnostic messages.}#
  (if (is_closure c)
      (setq diagv_tree c)))

(defun register_diag_basic_block (c)
  :doc #{Register a closure to handle @code{:basic_block} stuff in diagnostic messages.}#
  (if (is_closure c)
      (setq diagv_basic_block c)))

(defun register_diag_edge (c)
  :doc #{Register a closure to handle @code{:edge} stuff in diagnostic messages.}#
  (if (is_closure c)
      (setq diagv_edge c)))


(defclass class_diagnostic_state
  :super class_located
  :fields (diag_vect 
	   diag_position
	   diag_state)
  :doc #{The $CLASS_DIAGNOSTIC_STATE manage diagnostic handling by $ERROR and $WARNING ....}#
  )

;;; the discriminant for diagnostic closures
(definstance discr_diagnostic_closure class_discriminant
  :doc #{The $DISCR_DIAGNOSTIC_CLOSURE is the discriminant of MELT
  diagnostic manipulator functions, used in $ERROR, $WARNING,
  etc.... Use $CLONE_WITH_DISCRIMINANT on a closure, e.g. with
  $LAMBDA, to make it a diagnostic manipulator function.}#
  :disc_super discr_closure
  :named_name '"DISCR_DIAGNOSTIC_CLOSURE")


;;;;;;;;;;;;;;;;
;; usage (diagnostic_args_macro <nbargs-var> <vect-var>)
(defmacro diagnostic_args_macro (sexp env mexpander modctx)
  :doc #{Macro $DIAGNOSTIC_ARGS_MACRO to be invoked with two variables @var{nbargs} and @var{vect} to 
parse variadic arguments in diagnostic functions like $ERROR or $WARNING or $INFORM.}#
  (debug "diagnostic_args_macro sexp=" sexp)
  (shortbacktrace_dbg "diagnostic_args_macro" 12)
  (assert_msg "check sexp" (is_a sexp class_sexpr) sexp)
  (let (
	(sloc (get_field :loca_location sexp))
	(sexcont (get_field :sexp_contents sexp))
	)
    (assert_msg "check sexcont" (is_list sexcont) sexcont)
    (let ( 
	  (tcont (list_to_multiple sexcont discr_multiple))
	  (:long tcontlen (multiple_length tcont))
	  )
      (assert_msg "check tcont" (is_multiple tcont) tcont sexcont)
      (assert_msg "check tcontlen" (>i tcontlen 0) tcontlen tcont)
      (when (!=i tcontlen 3)
	(error_plain sloc "DIAGNOSTIC_ARGS_MACRO needs two args: <nbargs> <vect>")
	(code_chunk diagargbad_chk #{ /* diagnostic_args_macro $DIAGARGBAD_CHK */
		    melt_low_stderr_value ("diagnostic_args_macro sexp", $SEXP) ;
		    melt_low_stderr_value ("diagnostic_args_macro sexcont", $SEXCONT) ;
		    melt_low_stderr_value ("diagnostic_args_macro tcont", $TCONT) ;
		    melt_low_stderr_value ("diagnostic_args_macro sloc", $SLOC) ;
		    }#)
	(inform_strv sloc "DIAGNOSTIC_ARGS_MACRO called with " 
		     (string4out discr_string tcontlen " args == " tcont))
	(assert_msg "diagnostic_args_macro wrongly called when bootstrapping" 
		    (not (melt_is_bootstrapping)) sexp sexcont tcont)
	(return)
	)
      (let ( 
	    (sexpnbarg  (multiple_nth tcont 1))
	    (macrovarnbarg (mexpander sexpnbarg env mexpander modctx))
	    (sexpvarvect (multiple_nth tcont 2))
	    (macrovarvect (mexpander sexpvarvect env mexpander modctx))
	    )
	(when (is_not_a macrovarnbarg class_symbol)
	  (error_plain sloc 
		       "(DIAGNOSTIC_ARGS_MACRO <nbargs> <vect>) not variable <nbargs>")
	  (return))
	(when (is_not_a macrovarvect class_symbol)
	  (error_plain sloc 
		       "(DIAGNOSTIC_ARGS_MACRO <nbargs> <vect>) not variable <vect>")
	  (return))
	(let ( (resexp
		`(let ( 
		       (diagposbox (box 0))
		       (diagstate (instance class_diagnostic_state
					     :loca_location ,sloc
					     :diag_vect ,macrovarvect
					     :diag_position diagposbox
					     :diag_state (make_mapobject discr_map_objects 19)))
			)
		   (setq ,macrovarnbarg 0)
		   (forever 
		    argloop
		    (put_int diagposbox ,macrovarnbarg)
		    (variadic 
		     ( ()
		       (exit argloop))
		     ( (:cstring str)
		       (let ( (bs (constant_box str))
			      )
			 (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			 (multiple_put_nth ,macrovarvect ,macrovarnbarg bs)
			 )
		       (void)
		       )
		     ( (:long l)
		       (let ( (sn (string4out discr_string l))
			      )
			 (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			 (multiple_put_nth ,macrovarvect ,macrovarnbarg sn)
			 )
		       (void)
		       )
		     ( (:tree tr)
		       (assert_msg "check diagv_tree" (is_closure diagv_tree) diagv_tree)
		       (let ( (s (diagv_tree diagstate tr))
			      )
			 (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			 (multiple_put_nth ,macrovarvect ,macrovarnbarg s)
			 )
		       (void)
		       )
		     ( (:gimple gi)
		       (assert_msg "check diagv_gimple" (is_closure diagv_gimple) diagv_gimple)
		       (let ( (s (diagv_gimple diagstate gi))
			      )
			 (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			 (multiple_put_nth ,macrovarvect ,macrovarnbarg s)
			 )
		       (void)
		       )
		     ( (:gimple_seq gs)
		       (assert_msg "check diagv_gimple_seq" (is_closure diagv_gimple_seq) diagv_gimple_seq)
		       (let ( (s (diagv_gimple_seq diagstate gs))
			      )
			 (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			 (multiple_put_nth ,macrovarvect ,macrovarnbarg s)
			 )
		       (void)
		       )
		     ( (:basic_block bb)
		       (assert_msg "check diagv_basic_block" (is_closure diagv_basic_block) diagv_basic_block)
		       (let ( (s (diagv_basic_block diagstate bb))
			      )
			 (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			 (multiple_put_nth ,macrovarvect ,macrovarnbarg s)
			 )
		       (void)
		       )
		     ( (:edge ed)
		       (assert_msg "check diagv_edge" (is_closure diagv_edge) diagv_edge)
		       (let ( (s (diagv_edge diagstate ed))
			      )
			 (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			 (multiple_put_nth ,macrovarvect ,macrovarnbarg s)
			 )
		       (void)
		       )
		     ( (:value v)
		       (cond 
			( (is_integerbox v)
			  (let ( (sn (string4out discr_string (get_int v)))
				 )
			    (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			    (multiple_put_nth ,macrovarvect ,macrovarnbarg sn)
			    )
			  (void)
			  )
			( (is_string v)
			  (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			  (multiple_put_nth ,macrovarvect ,macrovarnbarg v)
			  (void)
			  )
			( (is_a v discr_diagnostic_closure)
			  (v diagstate)
			  (void)
			  )
			( (and (is_a v class_keyword)
			       (is_a (get_field :symb_data v) discr_diagnostic_closure)
			       )
			  ((get_field :symb_data v) diagstate)
			  (void)
			  )
			( (is_a v class_named)
			  (let ( (nam (unsafe_get_field :named_name v))
				 )
			    (assert_msg "check nam" (is_string nam) nam)
			    (setq ,macrovarnbarg (+ ,macrovarnbarg 1))
			    (multiple_put_nth ,macrovarvect ,macrovarnbarg nam)
			    )
			  (void)
			  )
			)
		       )
		     ( :else
		       (let ( (vcty (variadic_ctype 0))
			      )
			 (errormsg_strv "DIAGNOSTIC_ARGS_MACRO for unsupported ctype"
					(get_field :named_name vcty))
			 (assert_msg "invalid variadic argument to DIAGNOSTIC_ARGS_MACRO" () vcty))
		       (void)
		       )
		     ))			;end forever args
		   diagstate		;the result
		   )
		)			; end resexp binding
	       )
	  (let ( (mexp (mexpander resexp env mexpander modctx))
		 )
	    (put_fields mexp :loca_location sloc)
	    (debug "diagnostic_args_macro final mexp=" mexp)
	    (return mexp)
	    )
	  )
	)
      )
    )
  )
(export_macro diagnostic_args_macro)

(defun diagnostic_expand_message (diagstate :cstring sfmt)
  ;;(debug "diagnostic_expand_message diagstate=" diagstate " sfmt=" sfmt)
  (assert_msg "check diagstate" (is_a diagstate class_diagnostic_state) diagstate)
  (assert_msg "check sfmt" sfmt sfmt)
  (let ( (diagvec (get_field :diag_vect diagstate))
	 (:long dpos (get_int (get_field :diag_position diagstate)))
	 (:long spos 0)
	 (:long dollarpos 0)
	 (:long ixdoll -1)
	 (:long fmtlen 0)
	 (sbuf (make_strbuf discr_strbuf))
	 )
    (code_chunk slen_chk 
		#{/* diagnostic_expand_message $SLEN_CHK*/ $FMTLEN = (($SFMT)?strlen($SFMT):0);
		}#)
    (assert_msg "check diagvec" (is_multiple diagvec) diagvec)
    ;;(debug "diagnostic_expand_message sfmt=" sfmt " fmtlen=" fmtlen " diagvec=" diagvec)
    (assert_msg "check diagvec" (is_multiple diagvec) diagvec)
    (forever 
     diagloop
     (if (>=i spos fmtlen) 
	 (exit diagloop))
     (setq ixdoll -1)
     (code_chunk dolpos_chk
		 #{ /* diagnostic_expand_message $DOLPOS_CHK start */
		    const char *dp = strchr ($SFMT + $SPOS, '$$');
		    if (dp) {
                      $DOLLARPOS = dp - $SFMT;
		      if ($DOLLARPOS > $SPOS)
		         meltgc_add_out_cstr_len ($SBUF, $SFMT + $SPOS, $DOLLARPOS - $SPOS);
		      if (ISDIGIT(dp[1]))
		         $IXDOLL = dp[1] - '0';
		      else
		         meltgc_add_out_cstr_len ($SBUF, dp+1, 1);
		    } else {
		      meltgc_add_out_cstr ($SBUF, $SFMT + $SPOS);
                      $DOLLARPOS = -1;
		    }
		    /* end diagnostic_expand_message $DOLPOS_CHK */
		 }#)
     ;;(debug "diagnostic_expand_message dollarpos=" dollarpos " ixdoll=" ixdoll " dpos=" dpos)
     (when (<i dollarpos 0)
	 (exit diagloop))
     (if (<i ixdoll 0) 
	 (again diagloop))
     (if (<=i ixdoll dpos)
       (let ( (diagcomp (multiple_nth diagvec ixdoll))
	      )
	 ;;(debug "ixdoll=" ixdoll " diagcomp=" diagcomp)
	 (add2out sbuf diagcomp)))
     (setq spos (+i dollarpos 2))
     )					;end forever diagloop
    (let ( (diagmsg (strbuf2string discr_string sbuf))
	   )
      ;;(debug "diagnostic_expand_message gives diagmsg=" diagmsg)
      (return diagmsg))
  ))

(export_class class_diagnostic_state)
(export_values
 diagnostic_expand_message
 discr_diagnostic_closure
 register_diag_basic_block
 register_diag_edge 
 register_diag_gimple
 register_diag_gimple_seq 
 register_diag_tree 
 )

;; we use ERROR_AT, not error, because ERROR is a control exception
;; raising primitive in Common Lisp and we don't want that
;; confusion...
(defun error_at (loc :cstring fmt :rest) 
  :doc #{Variadic $ERROR_AT function to emit an error message for source location $LOC. The $FMT format
  string may contain @code{$$1} ... @code{$$9} to refer to the first,
  ... nineth argument (after $FMT).}#
  ;;(debug "error_at start loc=" loc " fmt=" fmt)
  (let ( (vect (make_multiple discr_multiple 9))
	 (:long nbargs 0)
	 (diagstate (diagnostic_args_macro nbargs vect))
	 )
    ;;(debug "error_at diagstate=" diagstate)
    (let ( (diagmsg (diagnostic_expand_message diagstate fmt))
	   )
      ;;(debug "error_at diagmsg=" diagmsg)
      (assert_msg "check diagmsg" (is_string diagmsg) diagmsg)
      (code_chunk error_chk
		  #{ /* start error_at $ERROR_CHK */
		  melt_error_str (($LOC), melt_string_str ($DIAGMSG), NULL);
		  /* end error_at $ERROR_CHK */ }#)
      (assert_msg "bootstrapping error" (not (melt_is_bootstrapping)))
    )))					;end ERROR_AT


(defun fatal_error_at (loc :cstring fmt :rest) 
  :doc #{Variadic $FATAL_ERROR_AT function to emit a fatal error message for source location $LOC. The $FMT format
  string may contain @code{$$1} ... @code{$$9} to refer to the first,
  ... nineth argument (after $FMT).}#
  ;;(debug "fatal_error_at start loc=" loc " fmt=" fmt)
  (let ( (vect (make_multiple discr_multiple 9))
	 (:long nbargs 0)
	 (diagstate (diagnostic_args_macro nbargs vect))
	 )
    ;;(debug "fatal_error_at diagstate=" diagstate)
    (let ( (diagmsg (diagnostic_expand_message diagstate fmt))
	   )
      ;;(debug "fatal_error_at diagmsg=" diagmsg)
      (assert_msg "check diagmsg" (is_string diagmsg) diagmsg)
      (code_chunk error_chk
		  #{ /* start fatal_error_at $ERROR_CHK */
		  if ($LOC)
		     melt_error_str (($LOC), "MELT fatal error", NULL);
		  melt_fatal_error ("fatal error: %s",
				    melt_string_str ($DIAGMSG));
		  /* end fatal_error_at $ERROR_CHK */ }#)
      (assert_msg "bootstrapping error" (not (melt_is_bootstrapping)))
    )))					;end ERROR_AT


(defun warning_at (loc :cstring fmt :rest) 
  :doc #{Variadic $WARNING_AT function to emit an warning message for source location $LOC. The $FMT format
  string may contain @code{$$1} ... @code{$$9} to refer to the first,
  ... nineth argument (after $FMT).}#
  ;;(debug "warning_at start loc=" loc " fmt=" fmt)
  (let ( (vect (make_multiple discr_multiple 9))
	 (:long nbargs 0)
	 (diagstate (diagnostic_args_macro nbargs vect))
	 )
    ;;(debug "warning_at diagstate=" diagstate)
    (let ( (diagmsg (diagnostic_expand_message diagstate fmt))
	   )
      ;;(debug "warning_at diagmsg=" diagmsg)
      (assert_msg "check diagmsg" (is_string diagmsg) diagmsg)
      (code_chunk warning_chk
		  #{ /* start warning_at $WARNING_CHK */
		  melt_warning_str (0, ($LOC), melt_string_str ($DIAGMSG), NULL);
		  /* end warning_at $WARNING_CHK */ }#)
    )))					;end WARNING_AT



(defun inform_at (loc :cstring fmt :rest) 
  :doc #{Variadic $INFORM function to emit an inform notice. The $FMT format
  string may contain @code{$$1} ... @code{$$9} to refer to the first,
  ... nineth argument (after $FMT).}#
  ;;(debug "inform_at start loc=" loc " fmt=" fmt)
  (let ( (vect (make_multiple discr_multiple 9))
	 (:long nbargs 0)
	 (diagstate (diagnostic_args_macro nbargs vect))
	 )
    ;;(debug "inform_at diagstate=" diagstate)
    (let ( (diagmsg (diagnostic_expand_message diagstate fmt))
	   )
      (debug "inform_at diagmsg=" diagmsg)
      (assert_msg "check diagmsg" (is_string diagmsg) diagmsg)
      (code_chunk inform_chk
		  #{ /* start inform_at $INFORM_CHK */
		  melt_inform_str (($LOC), melt_string_str ($DIAGMSG), NULL);
		  /* end inform_at $INFORM_CHK */ }#)
    )))					;end INFORM_AT

(export_values error_at fatal_error_at warning_at inform_at)

;;****************************************************************



(defselector is_recursively_constructible class_selector
  :doc #{The selector $IS_RECURSIVELY_CONSTRUCTIBLE tests if an 
expression can appear in $LETREC bindings.}#
  :formals (recv)
)
  
(defclass class_source_generator_device
  :doc #{The internal $CLASS_SOURCE_GENERATOR_DEVICE accumulate C code
  generator devices to test syntactically that they produce good
  enough code. field $SRCGEN_DEFIN gives the definition and
  $SRCGEN_REPR gives the internal representation.}#
  :super class_source
  :fields (srcgen_defin srcgen_repr)
)

(defclass class_source_lazy_macro_expansion
  :doc #{The internal $CLASS_SOURCE_LAZY_MACRO_EXPANSION handles the
  common case of forward reference applications and other stuff. The
  normalization step will actually do the macro expansion. Field
  $SLAZYMACRO_FUN is a closure thunk returning the macro-expanded
  result. $SLAZYMACRO_OPER is the operator, usually a bound name.}#
  :super class_source
  :fields (
	   slazymacro_fun
	   slazymacro_oper
	   ))

;;; superclass for source with a sequence of argument subexpressions
(defclass class_source_argumented_operator
  :doc #{The internal super-class $CLASS_SOURCE_ARGUMENTED_OPERATOR is
the super-class of many abstract syntax with a sequence of argument
subexpressions. Field $SARGOP_ARGS is the tuple of arguments.}#
  :super class_source
  :fields (sargop_args))
	
;;; source application 
(defclass class_source_apply
  :doc #{The internal $CLASS_SOURCE_APPLY is for function application abstract syntax. $SAPP_FUN is
  the applied function, $SARGOP_ARGS is the tuple of arguments.}#
  :super class_source_argumented_operator
  :fields (sapp_fun			;the function to apply
	   ))


;;; source message sending 
(defclass class_source_msend
  :doc #{The internal $CLASS_SOURCE_MSEND for message sending abstract
  syntax. $MSEND_SELSYMB is the message selector symbol, $MSEND_RECV
  is the receiver, $SARGOP_ARGS is the tuple of arguments.}#
  :super class_source_argumented_operator
  :fields ( 
	   msend_selsymb		;the selector symbol
	   msend_recv			;the receiver
	   ))

;;; source primitive invocation
(defclass class_source_primitive
  :doc #{The internal $CLASS_SOURCE_PRIMITIVE is for primitive
invocation abstract syntax. $SPRIM_OPER is the primitive operation,
$SARGOP_ARGS is the tuple of arguments.}#
  :super class_source_argumented_operator
  :fields (sprim_oper			;the primitive operation
	   ))

(defclass class_source_hook_call
  :doc #{The internal $CLASS_SOURCE_HOOK_CALL is for hook
call abstract syntax. $SHOOK_CALLED is the called hook or hook definition,
$SARGOP_ARGS is the tuple of arguments.}#
  :super class_source_argumented_operator
  :fields (shook_called			;the called hook
	   ))


;;; source arithmetic variadic operation
(defclass class_source_arithmetic_variadic_operation
  :doc #{The internal $CLASS_SOURCE_ARITHMETIC_VARIADIC_OPERATION is
  for expansion of variadic arithmetic operations like + - * /.}#
  :super class_source_argumented_operator
  :fields (sarithvar_neutral
	  sarithvar_primitive))

  
;;; source citerator invocation
(defclass class_source_citeration
  :doc #{The intenal $CLASS_SOURCE_CITERATION is for c-iteration
  abstract syntax. $SCRITER_OPER is the c-iterator, $SARGOP_ARGS is
  the tuple of arguments, $SCITER_VARBIND is the tuple of formal local
  bindings, and $SCITER_BODY is the tuple for the abstract body.}#
  :super class_source_argumented_operator
  :fields (sciter_oper			;the citerator operation
	   sciter_varbind		;tuple of formal local var bindings
	   sciter_body			;tuple for body
	   ))

;;; source cmatcher expression
(defclass class_source_cmatchexpr
  :doc #{The internal $CLASS_SOURCE_CMATCHEXPR is for c-matcher
expression abstract syntax. $SCMATX_CMATCHER is for the c-matcher,
$SCMATX_ARGS is for arguments.}#
  :super class_source_argumented_operator
  :fields (scmatx_cmatcher		;the cmatcher
	   ))

;; source funmatcher expression
(defclass class_source_funmatchexpr
  :doc #{The internal $CLASS_SOURCE_FUNMATCHEXPR is for funmatcher
expression abstract syntax. $SFMATX_FMATCHER is the funmatcher
$SFMATX_FMATBIND is the funmatcher binding, $SARGOP_ARGS is the
tuple of arguments.}#
  :super class_source_argumented_operator
  :fields (sfmatx_fmatcher		;the funmatcher
	   sfmatx_fmatbind		;the funmatcher binding
))

;;; source tuple
(defclass class_source_tuple
  :doc #{The internal $CLASS_SOURCE_TUPLE is for $TUPLE expression
 abstract syntax.  $SARGOP_ARGS is the tuple of arguments.}#
  :super class_source_argumented_operator
  :fields ())

;;; source list
(defclass class_source_list
  :doc #{The internal $CLASS_SOURCE_LIST is for $LIST expression
 abstract syntax.  $SARGOP_ARGS is the tuple of arguments.}#
  :super class_source_argumented_operator
  :fields ())

;;; source progn
(defclass class_source_progn
  :doc #{The internal $CLASS_SOURCE_PROGN is for $PROGN expression abstract syntax. 
$SPROGN_BODY is the body tuple.}#
  :super class_source
  :fields (sprogn_body			;the body tuple
	   ))

;;; source return
(defclass class_source_return
:doc #{The internal $CLASS_SOURCE_RETURN is for $RETURN expression
abstract syntax. The tuple of returned stuff is $SARGOP_ARGS.}#
  :super class_source_argumented_operator
  :fields ())

;;;; source setq
(defclass class_source_setq
  :doc #{The internal $CLASS_SOURCE_SETQ is for $SETQ expression
abstract syntax. $SSTQ_VAR is the assigned variable, $SSTQ_EXPR is
the expression.}#
  :super class_source
  :fields (sstq_var
	   sstq_expr))

;;;; source comment
(defclass class_source_comment
  :doc #{The internal $CLASS_SOURCE_COMMENT is for $COMMENT
  syntax. $SCOMM_STR is the comment string.}#
  :super class_source
  :fields (scomm_str
	   ))


;; superclass for cheader and cimplement
(defclass class_source_code_string
  :doc #{The internal abstract superclass $CLASS_SOURCE_CODE_STRING is
  for $C_HEADER and $C_IMPLEMENT }#
  :super class_source
  :fields (sc_codestring
	   )
)
;;; source module_is_gpl_compatible
(defclass class_source_module_is_gpl_compatible
  :doc #{The internal $CLASS_SOURCE_MODULE_IS_GPL_COMPATIBLE is for
  $MODULE_IS_GPL_COMPATIBLE syntax.}#
  :super class_source_code_string
  :fields ()
  )

;;;; source cheader
(defclass class_source_cheader
  :doc #{The internal $CLASS_SOURCE_CHEADER is for $C_HEADER abstract
syntax.  $S_CODESTRING gives the code string to add into the
declaration part. }#
  :super class_source_code_string
  :fields ()
)
;;;; source cimplement
(defclass class_source_cimplement
  :doc #{The internal $CLASS_SOURCE_CIMPLEMENT is for $C_IMPLEMENT abstract
syntax.  $S_CODESTRING gives the code string to add into the
implementation part. }#
  :super class_source_code_string
  :fields ()
)


;;;; source use_package_from_pkg_config
(defclass class_source_use_package_from_pkg_config
  :doc #{The internal $CLASS_SOURCE_USE_PACKAGE_FROM_PKG_CONFIG is for
$USE_PACKAGE_FROM_PKG_CONFIG abstract syntax.  $SUSEPACKAGE_PKGTUPLE
gives the tuple of pkg-config package string names. }#
  :super class_source
  :fields (susepackage_pkgtuple
	   )
)

;;;; source quote
(defclass class_source_quote
  :doc #{The internal $SCLASS_SOURCE_QUOTE is for $QUOTE abstract syntax. $SQUOTED is the quoted stuff.}#
  :super class_source
  :fields (squoted
	   ))

;;;; source box
(defclass class_source_quasi_box
  :doc #{The internal super-class $SCLASS_SOURCE_QUASI_BOX is for $BOX and $CONSTANT_BOX abstract syntax. $SBOXED is the boxed stuff.}#
  :super class_source
  :fields (sboxed
	   ))

(defclass class_source_box
  :doc #{The internal $SCLASS_SOURCE_BOX is for $BOX abstract syntax. $SBOXED is the boxed stuff.}#
  :super class_source_quasi_box
  :fields ())

(defclass class_source_constant_box
  :doc #{The internal $SCLASS_SOURCE_CONSTANT_BOX is for $CONSTANT_BOX abstract syntax. $SBOXED is the boxed stuff.}#
  :super class_source_quasi_box
  :fields ())


;;; source unbox
(defclass class_source_unbox
  :doc #{The $CLASS_SOURCE_UNBOX is for $UNBOX abstract
  syntax. $SUNBOX_CTYPE gives the c-type, and $SUNBOX_EXPR gives the
  expression to unbox.}#
  :super class_source 
  :fields (sunbox_ctype
	   sunbox_expr
	   ))




;; source export 
(defclass class_source_exportcommon
  :doc #{The internal $CLASS_SOURCE_EXPORTCOMMON is the common
super-class of abstract syntax of name-exporting directives. $SEXPORT_NAMES is the
tuple of exported names.}#
  :super class_source
  :fields (sexport_names
	   ))

;; export value
(defclass class_source_export_values
  :doc #{The internal $CLASS_SOURCE_EXPORT_VALUES is for the $EXPORT_VALUES directive.}#
  :super class_source_exportcommon
  :fields (
	   ))

;; export classes
(defclass class_source_export_class
  :doc #{The internal $CLASS_SOURCE_EXPORT_CLASS is for abstract
syntax of $EXPORT_CLASS directives.}#
  :super class_source_exportcommon
  :fields (
	   ))


(defclass class_source_export_any_macro
  :doc #{The internal $CLASS_SOURCE_EXPORT_ANY_MACRO is for abstract syntax of
$EXPORT_MACRO directives. $SEXPMAC_MNAME is the macro-name,
and $SEXPMAC_DOC is the
documentation.}#
  :super class_source
  :fields (sexpmac_mname
	   sexpmac_doc
	   ))

;; export one macro - (export_macro <macroname> <value>)
;; beware that the evaluation of the value is done near end of initial routine!
(defclass class_source_export_macro
  :doc #{The internal $CLASS_SOURCE_EXPORT_MACRO is for abstract
syntax of $EXPORT_MACRO directives with an explicit expanser.
$SEXPMAC_MVAL is the expanser value.}#
  :super class_source_export_any_macro
  :fields (sexpmac_mval
	   ))

;; export one defined macro - (export_macro <macroname>)
;; beware that the evaluation of the value is done near end of initial routine!
(defclass class_source_export_defmacro
  :doc #{The internal $CLASS_SOURCE_EXPORT_DEFMACRO is for abstract
syntax of $EXPORT_MACRO directives for macros defined with $DEFMACRO.}#
  :super class_source_export_any_macro
  :fields (
	   ))

;; export one pattern - (export_patmacro <macroname> <patexpvalue> <macexpvalue>)
;; beware that the evaluation of the value is done near end of initial routine!
(defclass class_source_export_patmacro
  :doc #{The internal $CLASS_SOURCE_EXPORT_PATMACRO is for abstract
syntax of $EXPORT_PATMACRO directive. $SEXPPAT_PVAL is the pattern
expander.}#
  :super class_source_export_macro
  :fields (
	   sexppat_pval			;value of patternexpander
	   ))



;;; export a synonym (export_synonym <newname> <oldname> [:doc <docum>)
(defclass class_source_export_synonym
  :doc #{$CLASS_SOURCE_EXPORT_SYNONYM represent synonym declarations: the
$SEXPSYN_NEWNAME is a new name synonym of $EXPSYN_OLDNAME and
documentation $SEXPSYN_DOC.}#
  :super class_source
  :fields (sexpsyn_newname
	   sexpsyn_oldname
	   sexpsyn_doc))


;;; superclass for all source definitions
(defclass class_source_definition
  :doc #{The internal common super-class for abstract syntax of all source definitions is
  $CLASS_SOURCE_DEFINITION. The field $SDEF_NAME is the defined name. The field
  $SDEF_DOC gives the optional documentation.}#  
  :super class_source
  :fields (sdef_name			;defined name
	   sdef_doc			;documentation string or list
	   ))

;;;; define a module variable
(defclass class_source_defvar
  :super class_source_definition
  :doc #{The $CLASS_SOURCE_DEFVAR defines a module variable, initialized to the nil value.}#
)

;;;; define a value
(defclass class_source_define
  :super class_source_definition
  :doc #{The $CLASS_SOURCE_DEFINE is for value definitions. Field
 $SDEFINE_BODY is the tuple of expressions of the value bound to
 $SDEF_NAME.}#
  :fields (sdefine_body))

;;; superclass for all definitions with formal arglist
(defclass class_source_definition_formal
  :doc #{The internal $CLASS_SOURCE_DEFINITION_FORMAL is the super-class of all definitions
with a formal arguments binding tuple given in $SFORMAL_ARGS.}# 
  :super class_source_definition
  :fields (sformal_args			;formal arguments binding tuple
	   ))

;;;; define a function
(defclass class_source_defun
  :doc #{The internal $CLASS_SOURCE_DEFUN is the abstract syntax of
  $DEFUN, and superclass of abstract syntax of $DEFMACRO.  $SFUN_BODY
  is the body tuple.}#
  :super class_source_definition_formal
  :fields (sfun_body			;body sequence
	   ))


;; define a macro
(defclass class_source_defmacro
  :doc #{The internal $CLASS_SOURCE_DEFMACRO is the abstract syntax of $DEFMACRO. $SMACRO_BINDING is the binding.}#
  :super class_source_defun
  :fields (smacro_binding			;body sequence
	   ))

(defclass class_source_defmacro_in_let
  :doc #{The internal $CLASS_SOURCE_DEFMACRO_IN_LET is for delayed expansion of :macro let bindings.}#
  :super class_source_defmacro
  :fields (smacro_sourceletbinding)
  )

(defclass class_defined_macro_binding
  :doc #{The internal $CLASS_DEFINED_MACRO_BINDING is for macros defined with $DEFMACRO.}#
  :super class_macro_binding
  :fields (
	   mbind_defmacro
	   mbind_data
	   ))

(defclass class_source_macro_installation
  :super class_source
  :doc #{The $CLASS_SOURCE_MACRO_INSTALLATION, for gurus, is an
  internal class used to install macros. $SMACINST_DEFMACRO is the
  macro definition and $SMACINST_ENV is the environment.}#
  :fields (smacinst_defmacro
	   smacinst_env))

;;; define a primitive
(defclass class_source_defprimitive
  :doc #{The internal $CLASS_SOURCE_DEFPRIMITIVE is the abstract
syntax of $DEFPRIMITIVE.  $SPRIM_TYPE is the result ctype,
$SPRIM_EXPANSION is the tuple of its expansion and $SPRIM_EXPLOC is
the location of the expansion.}#
  :super class_source_definition_formal
  :fields (sprim_type			;result type of primitive
	   sprim_expansion		;primitive expansion
	   sprim_exploc			;precise location of expansion
	   ))

;; define a hook
(defclass class_source_defhook
  :doc #{The internal $CLASS_SOURCE_DEFHOOK is the abstract syntax for
  $DEFHOOK. Inherited $SFORMAL_ARGS are the input formals, and
  $SHOOK_OUT_FORMALS are the output formals, $SHOOK_CTYPE is the
  result ctype, $SHOOK_PREDEF is the optional predefined slot,
  $SHOOK_VARIABLE is the optional module variable, and $SHOOK_BODY is
  the body. }#
  :super class_source_definition_formal
  :fields (shook_out_formals shook_ctype shook_predef shook_variable shook_body))

;;; define a citerator
(defclass class_source_defciterator
  :doc #{The internal $CLASS_SOURCE_DEFCITERATOR is the abstact syntax
of $DEFCITERATOR.  $SCITERDEF_CITERATOR is the c-iterator, $SCITERDEF_BEFORELOC is the location of the before chunk, and $SCRITERDEF_AFTERLOC is the location of the after chunk}#
  :super class_source_definition_formal		;the sformal_args is the start arguments
  :fields (sciterdef_citerator		;the citerator
	   sciterdef_beforeloc		;location of before
	   sciterdef_afterloc		;location of after
	   ))

;;; define a cmatcher
(defclass class_source_defcmatcher
  :doc #{The internal $CLASS_SOURCE_DEFCMATCHER is the abstract syntax
of $DEFCMATCHER. $SCMATDEF_CMATCHER is the
c-matcher. $SCMATDEF_TESTLOC is the location of the test expansion,
$SCMATDEF_FILLLOC is the location of the fill expansion, and
$SCMATDEF_OPERLOC is the location of the optional operator
expansion.}#
  :super class_source_definition_formal
  :fields (;;loca_location is the location
	   ;;sdef_name is the new cmatcher name
	   ;;sformal_args is for the matched formal & input arguments
	   ;;;;the first formal is for the matched stuff. The rest is for input
	   scmatdef_cmatcher		;the cmatcher
	   scmatdef_testloc		;location of test expansion
	   scmatdef_fillloc 		;location of fill expansion
	   scmatdef_operloc		;location of operator expansion
	   ))

;;; define a funmatcher
(defclass class_source_defunmatcher
  :doc #{The internal $CLASS_SOURCE_DEFUNMATCHER is the abstract
syntax of $DEFUNMATCHER. $SFUMATDEF_INS is the input formals
tuple. $SFUNMATDEF_OUTS is the output formals tuple. $SFUMATDEF_MATCHF
is the matcher function expression. $SFUNMATDEF_APPLYF is the the
applying function expression. $SFUMATDEF_DATA is some extra data.}#
  :super class_source_definition_formal
  :fields (;;loca_location is the location
	   ;;sdef_name is the new cmatcher name
	   ;;sformal_args is for matched formal & input arguments
	   ;;;;the first formal is for the matched stuff. The rest is for input
	   sfumatdef_ins		;the ins formals (rest of sformal_args)
	   sfumatdef_outs		;output argument list
	   sfumatdef_matchf		;the matcher function expr
	   sfumatdef_applyf		;the applying function expr
	   sfumatdef_data		;supplementary data expr
	   ))


;; define an object (common to instance, class, selector)
(defclass class_source_defobjcommon
  :doc #{The internal $CLASS_SOURCE_DEFOBJCOMMON is the common superclass for
  object definitions. $SOBJ_PREDEF is the predefined rank if any.}#
  :super class_source_definition
  :fields (sobj_predef			;the predefined rank
	   ))

;; define a class 
;;;; the class has been built (at compile time), but we need a
;;;; srcdefclass to actually generate code
(defclass class_source_defclass
  :doc #{The internal $CLASS_SOURCE_DEFCLASS is the $DEFCLASS
abstract syntax. $SCLASS_CLABIND is the binding of the class,
$SCLASS_SUPERBIND is the binding of the superclass, $SCLASS_FLDBIND is
the sequence of own field bindings.}#
  :super class_source_defobjcommon
  :fields (sclass_clabind		;the binding of the class
	   sclass_superbind		;binding of superclass (or nil if none)
	   sclass_fldbinds		;the sequence of (own field bindings)
	   ))


;; define an instance
(defclass class_source_definstance
  :doc #{The internal $CLASS_SOURCE_DEFINSTANCE is the $DEFINSTANCE
abstract syntax. $SINST_CLASS the class of the defined instance,
$SINST_CLABIND is its binding, $SINST_OBJNUM if for the object magic
number, $SINST_FIELDS is the sequence of field assignments of
$CLASS_SOURCE_FIELDASSIGN.}#
  :super class_source_defobjcommon
  :fields (sinst_class			;the class of the instance
	   sinst_clabind		;the classbinding of the instance
	   sinst_objnum			;the object number symbol or integer
	   sinst_fields			;the sequence of field assignment
	   ))

;; define a selector 
(defclass class_source_defselector
  :doc #{The internal $CLASS_SOURCE_DEFSELECTOR is the $DEFSELECTOR abstract syntax. $SDEFSEL_FORMALS
is the formal argument bindings signature sequence, if any.}#
  :super class_source_definstance
  :fields (sdefsel_formals		;the formal arguments as signature
	   )
  )

;; a field assignment
(defclass class_source_fieldassign
  :doc #{The internal $CLASS_SOURCE_FIELDASSIGN is the abstract syntax
for field assigments inside e.g. $DEFINSANCE. $SFLA_FIELD is the
field, $SFLA_EXPR is the expression.}#
  :super class_source
  :fields (sfla_field			;the field 
	   sfla_expr			;the expression
	   ))


;; make an instance
(defclass class_source_instance
  :doc #{The internal $CLASS_SOURCE_INSTANCE is the abstract
syntax of $INSTANCE expressions.  $SMINS_CLASS is the class of the new
object, $SMINS_CLABIND is the class binding, $SMINS_FIELDS is the
sequence of $CLASS_SOURCE_FIELDASSIGN.}#
  :super class_source
  :fields (smins_class			;the class to be instantiated
	   smins_clabind		;its (class|value) binding
	   smins_fields			;the sequence of field assignment
	   ))

;;; source  get field
(defclass class_source_get_field
  :doc #{The internal $CLASS_SOURCE_GET_FIELD is the abstract syntax
  of $GET_FIELD. $SUGET_OBJ is the object expression, $SUGET_FIELD is
  the accessed field.}#
  :super class_source
  :fields (suget_obj	     ;the object expression
	   suget_field	     ;the field 
	   ))


;;; source unsafe get field
(defclass class_source_unsafe_get_field
  :doc #{The internal $CLASS_SOURCE_UNSAFE_GET_FIELD is the abstract
syntax of $UNSAFE_GET_FIELD. See $CLASS_SOURCE_GET_FIELD.}#
  :super class_source_get_field
  :fields ())

;;; source get field

;; source put fields
(defclass class_source_put_fields
  :doc #{The internal $CLASS_SOURCE_UNSAFE_PUT_FIELDS is the abstract
syntax of $PUT_FIELDS. $SUPUT_OBJ is the object expression,
$SUPU_FIELDS is the sequence of $CLASS_SOURCE_FIELDASSIGN.}#
  :super class_source
  :fields (suput_obj	     ;the object expression
	   suput_fields			;the sequence of field assignment
	   ))

;; source unsafe put fields
(defclass class_source_unsafe_put_fields
  :doc #{The internal $CLASS_SOURCE_UNSAFE_PUT_FIELDS is the abstract
syntax of $UNSAFE_PUT_FIELDS. See $CLASS_SOURCE_PUT_FIELDS.}#
  :super class_source_put_fields
  :fields (
	   ))


;; a conditional (if, and, cond)
(defclass class_source_if
  :doc #{The internal $CLASS_SOURCE_IF is the abstract syntax of
  conditionals like $IF $AND $COND. $SIF_TEST is the test, and
  $SIF_THEN is the then part. See also $CLASS_SOURCE_IFELSE.}#
  :super class_source
  :fields (sif_test
	   sif_then
	   ))

(defclass class_source_ifelse
  :doc #{The internal $CLASS_SOURCE_IFELSE is the abstract syntax of
conditionals with else part like some $IF $AND $COND. The $SIF_ELSE
is the else part. See also $CLASS_SOURCE_IF.}#
  :super class_source_if
  :fields ( sif_else
	    ))

;; an or
;;; since (OR a1 a2) is (IF a1 a1 a2) we need to normalize it to avoid evaluating twice a1
;;; so there is no normalized or... (only normalized if-s)
(defclass class_source_or
  :doc #{The internal $CLASS_SOURCE_OR is the abstract syntax of $OR
conditionals. $SOR_DISCJ is the tuple of disjuncts. See also
$CLASS_SOURCE_IF.}#
;;; we don't use class_source_argumented_operator because the
;;; arguments are used lazily, so they are really disjuncts...
  :super class_source
  :fields (sor_disj			;tuple of disjuncts
	   ))


;; preprocessor conditional
(defclass class_source_cppif
  :doc #{The internal $CLASS_SOURCE_CPPIF is the abstract syntax of $CPPIF preprocessor conditionals. 
$SIFP_COND is the preprocessor symbol. $SIFP_THEN is the then part. $SIFP_ELSE is the else part.}#
  :super class_source
  :fields (sifp_cond			;C preprocessor symbol or verbatim string to test
	   sifp_then			;then clause
	   sifp_else			;else clause
	   ))

;;;;;;;;;;;;;;;;
;; match 
(defclass class_source_match
  :doc #{The internal $CLASS_SOURCE_MATCH is the abtract syntax of
$MATCH expressions.  $SMAT_MATCHEDX is the matched
expression. $SMAT_CASES is the tuple of match-cases of
$CLASS_SOURCE_CASEMATCH.}#
  :super class_source
  :fields (smat_matchedx		;matched expression
	   smat_cases			;match case tuple
	   ))


;; NOTE [January 2013] We have a buggy match implementation. The
;; DSL2011 paper http://gcc-melt.org/MELT-Starynkevitch-DSL2011.pdf is
;; giving a better match implementation, still unfinished. To ease
;; development of the alternative (and better) match implementation we
;; use the temporary MATCHALT syntax.
(defclass class_source_matchalt 
  :doc #{the internal $CLASS_SOURCE_MATCHALT is temporary, for
  $MATCHALT expressions which should behave like $MATCH. See
  $CLASS_SOURCE_MATCH.}#
  :super class_source_match
  :fields ())

;;;;;;;;;;;;;;;;

;; match case
(defclass class_source_match_case
  :doc #{The internal $CLASS_SOURCE_MATCH_CASE is the abstract syntax of match-cases. $SCAM_PATT is the pattern, $SCAM_BODY is the body tuple.}#
  :super class_source
  :fields (scam_patt			;pattern
	   scam_body			;body
	   ))

;;;;;;;;;;;;;;;;

;;; letbinding source - not a binding, just abstract syntax for them
(defclass class_source_any_let_binding
  :doc #{The internal $CLASS_SOURCE_ANY_LET_BINDING is abstract syntax for 
  $LET bindings in the source.}#
  :super class_source
  :fields (sletb_binder
	   ))

(defclass class_source_macro_let_binding
  :doc #{The internal $CLASS_SOURCE_MACRO_LET_BINDING is abstract syntax for macro $LET binding in the source.}#
  :super class_source_any_let_binding
  :fields (sletm_macro_formals
	   sletm_macro_body))

;;; letbinding source - not a binding, just abstract syntax for them
(defclass class_source_let_binding
  :doc #{The internal $CLASS_SOURCE_LET_BINDING is abstract syntax for
  $LET bindings [of things] in the source. The $SLETB_TYPE gives the
  type of the binding, the $SLETB_BINDER gives the binder, and the
  $SLETB_EXPR gives the bound expression.}#
  :super class_source_any_let_binding
  :fields (sletb_type			;the type of the binding
	   sletb_expr			;the expression
	   ))


(defclass class_source_let_binding_for_macro
  :doc #{The internal $CLASS_SOURCE_LET_BINDING_FOR_MACRO is abstract
  syntax for $LET bindings [of things] in the source. The $SLETB_TYPE
  is $CTYPE_VALUE, the $SLETB_BINDER gives the binder,
  and the $SLETB_EXPR gives the bound lambda-expression. Field
  $SLETM_MACROLETBIND gives the instance of
  $CLASS_SOURCE_MACRO_LET_BINDING.}#
  :super class_source_let_binding
  :fields (sletfm_macroletbind))


(defclass class_source_letrec_binding
  :doc #{The internal $CLASS_SOURCE_LETREC_BINDING is abstract syntax for $LETREC bindings in the source.}#
  :super class_source_let_binding
  :fields ())

;; let source
(defclass class_source_let
  :doc #{The internal $CLASS_SOURCE_LET is for abstract syntax of
$LET. The $SLET_BINDINGS field is the tuple of bindings as instances
of $CLASS_SOURCE_LET_BINDING and the $SLET_BODY field is the tuple of
body.}#
  :super class_source
  :fields (slet_bindings		;the tuple of letbinding-s
	   slet_body			;the body tuple 
	   ))

(defclass class_source_letrec
  :doc #{The internal $CLASS_SOURCE_LETREC is for abstract syntax of
  $LETREC. The $SLET_BINDINGS are restricted to constructible
  expressions bindings}#
  :super class_source_let
  :fields ())

;; lambda
(defclass class_source_lambda
  :doc #{The internal $CLASS_SOURCE_LAMBDA is for abstract syntax of
  $LAMBDA. The $SLAM_ARGBIND is the tuple of formals
  $CLASS_FORMAL_BINDING and the $SLAM_BODY is the tuple of body
  expressions.}#
  :super class_source 
  :fields (slam_argbind			;tuple of argument bindings
	   slam_body			;tuple for body
	   ))

;; lambda
(defclass class_source_lambda_for_macro
  :doc #{The internal $CLASS_SOURCE_LAMBDA_FOR_MACRO is for abstract
  syntax of macro lambdas. Field $SLAM_ORIGMACRO gives the original
  macro or macrobinding}#
  :super class_source_lambda
  :fields (slam_origmacro)
  )

(defclass class_source_ifvariadic
  :doc #{The internal $CLASS_SOURCE_IFVARIADIC is for abstract syntax of
  $VARIADIC. The $SIFVARIADIC_ARGBIND is the tuple of formals of
  $CLASS_FORMAL_BINDING, and the $SIFVARIADIC_THEN is the tuple of body
  expressions evaluated with the variadics bound, otherwise $SIFVARIADIC_ELSE.}#
  :super class_source
  :fields (sifvariadic_argbind		;tuple for variadic formals
	   sifvariadic_then		;tuple for body
	   sifvariadic_else
	   ))

;; multicall
(defclass class_source_multicall
  :doc #{The internal $CLASS_SOURCE_MULTICALL is for abstract syntax
of $MULTICALL. The tuple of formal bindings of result variables is
$SMULC_RESBIND. The called abstract syntac is $SMULC_CALL, and the
body is $SMULC_BODY.}#
  :super class_source
  :fields (smulc_resbind		;tuple of argument bindings for multiple results
	   smulc_call			;called stuff
	   smulc_body			;tuple for body
	   ))

;;; forever, again & exit share a common label
(defclass class_source_labelled
  :doc #{The internal $CLASS_SOURCE_LABELLED is the super-class of
abstract syntax dealing with labels like $FOREVER and $EXIT. The
field $SLABEL_BIND gives the label binding.}#
  :super class_source
  :fields (slabel_bind			;the label binding
	   ))

;; forever
(defclass class_source_forever
  :doc #{The internal $CLASS_SOURCE_FOREVER is for abstract syntax of
  $FOREVER loops. The field $SFRV_BODY is the body sequence.}#
  :super class_source_labelled
  :fields (sfrv_body			;tuple for body
	   ))

;; again
(defclass class_source_again
  :doc #{The internal $CLASS_SOURCE_AGAIN is for abstract syntax of
  $AGAIN. $SLABEL_BIND gives the restarted loop label binding.}#
  :super class_source_labelled
  :fields ())

;; exit
(defclass class_source_exit
  :doc #{The internal $CLASS_SOURCE_EXIT is for abstract syntax of
$EXIT loops. The field $SEXI_BODY is the body sequence.}#
  :super class_source_labelled
  :fields ( sexi_body			;tuple for body
	    ))

;; compile time diagnostics
(defclass class_source_compile_diagnostic
  :doc #{The interal abstract $CLASS_SOURCE_COMPILER_DIAGNOSTIC is for
  compile time diagnostic message.}#
  :super class_source
  :fields (scdiag_msg
	   scdiag_expr))

;; compile time warning
(defclass class_source_compile_warning
  :doc #{The interal abstract $CLASS_SOURCE_COMPILER_WARNING is for
  compile time diagnostic message.}#
  :super class_source_compile_diagnostic
  :fields ())
(export_synonym class_source_compilewarning class_source_compile_warning)
;; compile time error
(defclass class_source_compile_error
  :super class_source_compile_diagnostic
  :fields ())

;; the fresh current module environment box, returning the newly build
;; module environment result of the generated initial routine
(defclass class_source_current_module_environment_reference
  :super class_source
  :fields (
	   cmec_comment		;extra comment
	   ))

;; the fres previous module environment, returning the argument passed
;; to the generated start_module_melt
(defclass class_source_parent_module_environment
  :super class_source
  :fields (
	   ))


;; update the current module environment container - only callable at
;; toplevel
(defclass class_source_update_current_module_environment_reference
  :super class_source
  :fields (
	   sucme_comment		;optional comment, only used
					;for internally generated ...
	   ))


;;; fetch a predefined by its name or rank
(defclass class_source_fetch_predefined
  :super class_source
  :fields (sfepd_predef
	   ))

;; store into a predefined
(defclass class_source_store_predefined
  :super class_source
  :fields (sstpd_predef
	   sstpd_value
	   ))


;; source code protochunk
(defclass class_source_protochunk
  :super class_source
  :fields (sch_gensym			;generating symbol
	   sch_chunks			;the chunks
))


;; source code chunk
(defclass class_source_codechunk
  :super class_source_protochunk
  :fields (
))

;; source expression chunk
(defclass class_source_exprchunk
  :super class_source_protochunk
  :fields (sxch_ctype
	   ))

;;;;;;;;;;;;;;;;
;;; source patterns
(defclass class_source_pattern
  :doc #{Common internal super-class $CLASS_SOURCE_PATTERN for
abstract syntax of patterns. The $PAT_WEIGHT field contains the weight
of the pattern, in a boxed integer.}#
  :super class_source
  :fields (pat_weight
	   ))

;;; or patterns
(defclass class_source_pattern_or
  :doc #{The internal $CLASS_SOURCE_PATTERN_OR is for abstract syntax
of $OR patterns. Pattern syntax is ?(OR subpattern...). Field
$ORPAT_DISJ gives the tuple of pattern disjuncts.}#
  :super class_source_pattern
  :fields (orpat_disj		    ;tuple of pattern disjuncts
))

;;; and patterns
(defclass class_source_pattern_and
  :super class_source_pattern
  :doc #{The internal $CLASS_SOURCE_PATTERN_AND is for abstract syntax
of $AND patterns. Pattern syntax is ?(AND subpattern...). Field
$ANDPAT_CONJ gives the tuple of pattern conjuncts.}#
  :fields (andpat_conj			;tuple of pattern conjoncts
))

;;; when patterns
(defclass class_source_pattern_when
  :super class_source_pattern
  :doc #{The internal $CLASS_SOURCE_PATTERN_WHEN is for abstract
syntax of tested patterns. Pattern syntax is ?(WHEN sub-pattern
condition). Field $WHENPAT_SUBPAT is the sub-pattern and $WHENPAT_COND
is the condition.}#
  :fields (whenpat_subpat 
	   whenpat_cond))



;;; simple source pattern variable
(defclass class_source_pattern_variable
  :doc #{The internal $CLASS_SOURCE_PATTERN_VARIABLE is for pattern
variable abstract syntax. The field $SPATVAR_SYMB gives the variable symbol. 
The field $SPATVAR_NBOCC is the boxed occurrence count.}#
  :super class_source_pattern
  :fields (spatvar_symb
	   spatvar_nbocc
	   ))
(export_synonym spat_var spatvar_symb)

;;; the joker source pattern variable
(defclass class_source_pattern_joker_variable
  :doc #{The internal $CLASS_SOURCE_PATTERN_JOKER_VARIABLE is for joker pattern abstract syntax.}#
  :super class_source_pattern_variable
  :fields (
	   ))

;;; simple source pattern constant
(defclass class_source_pattern_constant
  :doc #{The internal $CLASS_SOURCE_PATTERN_CONSTANT is for constant
pattern abstract syntax. The field $SPAT_CONSTX is the expression
giving the constant.}#
  :super class_source_pattern
  :fields (spat_constx			;expression giving the constant
	   ))
;;; simple source pattern constant

(defclass class_source_pattern_construct
  :doc #{The internal $CLASS_SOURCE_PATTERN_CONSTRUCT is the superclass for
constructive pattern abstract syntax. The field $CTPAT_SUBPA is for
sub-patterns abstract syntax.}#
  :super class_source_pattern
  :fields (ctpat_subpa			;sub-patterns
	   ))

;; tuple patterns
(defclass class_source_pattern_tuple
  :doc #{The internal $CLASS_SOURCE_PATTERN_TUPLE is for $TUPLE
pattern abstract syntax.}#
  :super class_source_pattern_construct
  :fields ())

;; list patterns
(defclass class_source_pattern_list
  :doc #{The internal $CLASS_SOURCE_PATTERN_LIST is for $LIST
pattern abstract syntax.}#
  :super class_source_pattern_construct
  :fields ())

;; simple source pattern for objects - with a sequence of fieldpatterns
;; matches an object whose class is spat_class or a subclass of it
(defclass class_source_pattern_object
  :doc #{The internal $CLASS_SOURCE_PATTERN_OBJECT is for $OBJECT
pattern abstract syntax. $SPAT_CLASS gives the class, and
$SPAT_FIELDS give the sequence of field patterns. See also
$CLASS_SOURCE_PATTERN_INSTANCE and $CLASS_SOURCE_FIELD_PATTERN.}#
  :super class_source_pattern
  :fields (spat_class			;required [super*] class
	   spat_fields			;sequence of fieldpatterns
	   ))

;; simple source pattern for exact instance
;; matches an object whose class is exactly spat_class
(defclass class_source_pattern_instance
  :doc #{The internal $CLASS_SOURCE_PATTERN_INSTANCE is for $INSTANCE
pattern abstract syntax. See also $CLASS_SOURCE_PATTERN_OBJECT for
field details.}#
  :super class_source_pattern_object
  :fields ( ))

;; simple field pattern
(defclass class_source_field_pattern
  :doc #{The internal $CLASS_SOURCE_FIELD_PATTERN is for abstract
syntax of fields inside patterns like $INSTANCE or $OBJECT. The
$SPAF_FIELD is the required field, and the $SPAF_PATTERN gives the
matching sub-pattern.}#
  :super class_source
  :fields (spaf_field			;the required field
	   spaf_pattern			;the pattern matching the field
	   ))

;; abstract composite source pattern
(defclass class_source_pattern_composite
  :doc #{The internal $CLASS_SOURCE_PATTERN_COMPOSITE is abstract
syntax for composite patterns with matchers. The $SPAC_OPERATOR field
gives the pattern operator, the $SPAC_OPERBIND is an optional operator
binding. The $SPAC_INARGS are the input sub-expressions. The
$SPAC_OUTARGS are the output sub-patterns.}#
  :super class_source_pattern_object
  :fields (spac_operator		;pattern operator
	   ;;;; the operator binding is useful to compile some
	   ;;;; composites (e.g. funmatching) and is better here,
	   ;;;; since it is closely related to the operator
	   spac_operbind		;operator binding (if any)
	   spac_inargs			;input expressions
	   spac_outargs			;output subpatterns
	   ))

;; anymatcher composite source pattern
(defclass class_source_pattern_matcher
  :doc #{The internal $CLASS_SOURCE_PATTERN_MATCHER is for abstract syntax of pattern with any kind of matchers.}#
  :super class_source_pattern_composite
  :fields ())

;; cmatcher composite source pattern
(defclass class_source_pattern_c_match
  :doc #{The internal $CLASS_SOURCE_PATTERN_C_MATCH is for abstract syntax of pattern with c-matchers.}#
  :super class_source_pattern_matcher
  :fields ())

;; funmatcher composite source pattern
(defclass class_source_pattern_fun_match
  :doc #{The internal $CLASS_SOURCE_PATTERN_FUN_MATCH is for abstract syntax of pattern with fun-matchers.}#
  :super class_source_pattern_matcher
  :fields ())



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; compute the recursive weight of an s-expr (or give :true if too big)
(defun s_expr_weight (topsexpr)
  :doc #{Return some weight of the given sexpr $TOPSEXPR or null if too big}#
  (letrec ( (recweight
	     (lambda (arg :long cum max)
	       (if (is_a arg class_sexpr)
		   (let ( (cont (get_field :sexp_contents arg))
			  (:long contlen (list_length cont))
			  (:long newcum (+i (+i contlen 1) cum))
			  )
		     (if (>i newcum max)
			 (return () newcum)
		       (progn
			 (foreach_pair_component_in_list
			  (cont)
			  (curpair curelem)
			  (multicall
			   (nres :long nw)
			   (recweight curelem newcum max)
			   (setq newcum nw)
			   (if (null nres) (return () newcum))))
			 (return :true newcum))))
		 (return :true cum))))
	    )
    (multicall
     (res :long w)
     (recweight topsexpr 0 6000)
     (if res (make_integerbox discr_constant_integer w) ()))))
	    
		       
		       
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;; first pass, macro expansion


(defun expand_restlist_as_list (arglist env mexpander modctx)
  :doc #{Expand all but the first in an argument list $ARGLIST in
  environment $ENV using expander $MEXPANDER as a list of macro
  expansions.}#
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check arglist" (is_list arglist) arglist)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (expreslist (list)) 
	 (:long count 0)
	 )
    (foreach_pair_component_in_list
     (arglist)
     (curpair curarg)
     (if (>i count 0)
	 (multicall 
	  (curexp xtraexp)
	  (mexpander curarg env mexpander modctx)
	  (cond ( (is_object curexp)
		  (list_append expreslist curexp))
		( (is_list curexp)
		  (list_append2list expreslist curexp))
		( (is_multiple curexp)
		  (foreach_in_multiple
		   (curexp)
		   (curcomp :long cix)
		   (list_append expreslist curcomp)))
		(:else
		 (list_append expreslist curexp)))
	  (cond 
	   ((is_multiple xtraexp)
	    (foreach_in_multiple
	     (xtraexp)
	     (curxtra :long xix)
	     (list_append expreslist curxtra)
	     ))
	   ((is_list xtraexp)
	    (foreach_pair_component_in_list
	     (xtraexp)
	     (xtrapair curxtra)
	     (list_append expreslist curxtra)
	     ))
	   (xtraexp
	    (list_append expreslist xtraexp))
	   )
	  )
       )
     (setq count (+i count 1))
     )
    (return expreslist)
    )
  )

;;expand all but the first element of a list as a tuple
(defun expand_restlist_as_tuple (arglist env mexpander modctx)
  :doc #{$EXPAND_RESTLIST_AS_TUPLE macro-expands all but the first element of a list as a tuple.}#
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check arglist" (is_list arglist) arglist)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (expreslist (expand_restlist_as_list arglist env mexpander modctx))
	 )
    (list_to_multiple expreslist discr_multiple)))



;;expand all of a pairlist as a list
(defun expand_pairlist_as_list (pair env mexpander modctx)
  :doc #{$EXPAND_RESTLIST_AS_TUPLE macro-expands a pair-list as a list.}#
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (expreslist (list)) 
	 )
    (forever exploop
	     (if (not (is_pair pair)) (exit exploop))
	     (let ( (curarg (pair_head pair))
		    )
	       (setq pair (pair_tail pair))
	       (multicall 
		(curexp xtraexp)
		(mexpander curarg env mexpander modctx)
		(cond ( (is_multiple curexp)
			(foreach_in_multiple
			 (curexp)
			 (curcomp :long cix)
			 (list_append expreslist curcomp))
			(void)
			)
		      ( (is_list curexp)
			(foreach_pair_component_in_list
			 (curexp)
			 (curpair curcomp)
			 (list_append expreslist curcomp)
			 )
			(void))
		      (:else
		       (list_append expreslist curexp)))
		(cond 
		 ((is_multiple xtraexp)
		  (foreach_in_multiple
		   (xtraexp)
		   (curxtra :long xix)
		   (list_append expreslist curxtra)
		   ))
		 ((is_list xtraexp)
		  (foreach_pair_component_in_list
		   (xtraexp)
		   (xtrapair curxtra)
		   (list_append expreslist curxtra)
		   ))
		 (xtraexp
		  (list_append expreslist xtraexp))
		 )
		)
	       )
	     )
    (return expreslist)
    )
  )


(defun expand_pairlist_as_tuple (pair env mexpander modctx)
  :doc #{$EXPAND_PAIRLIST_AS_TUPLE macroexpands a pair-list as a tuple.}#
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (is_pair pair)
      (let ( (expreslist (expand_pairlist_as_list pair env mexpander modctx))
	     )
	(list_to_multiple expreslist discr_multiple))))


(defun expand_tuple_slice_as_tuple (tuple :long startix endix :value env mexpander modctx)
  :doc #{$EXPAND_TUPLE_SLICE_AS_TUPLE macro-expands in given $TUPLE the slice from $STARTIX to $ENDIX}#
  (debug "expand_tuple_slice_as_tuple tuple=" tuple "\n ... startix#" startix " endix#" endix)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (is_multiple tuple)
      (let ( (:long tuplen (multiple_length tuple))
	     (expreslist (make_list discr_list))
	     )
	(if (<i startix 0) (setq startix (+i startix tuplen)))
	(if (<i endix 0) (setq endix (+i endix tuplen)))
	(debug "expand_tuple_slice_as_tuple updated startix=" startix " endix=" endix " tuplen=" tuplen)
	(if (>=i startix 0)
	    (if (<i endix tuplen)
		(when (<=i startix endix)
		  (foreach_long_upto
		   (startix endix)
		   (:long ix)
		   (let ( (curcomp (multiple_nth tuple ix))
			  )
		     (debug "expand_tuple_slice_as_tuple ix#" ix " curcomp=" curcomp)
		     (multicall 
		      (curexp xtraexp)
		      (mexpander curcomp env mexpander modctx)
		      (debug "expand_tuple_slice_as_tuple  ix#" ix " curexp=" curexp " xtraexp=" xtraexp)
		      (list_append expreslist curexp)
		      (cond 
		       ((is_multiple xtraexp)
			(foreach_in_multiple
			 (xtraexp)
			 (curxtra :long xix)
			 (list_append expreslist curxtra)
			 ))
		       ((is_list xtraexp)
			(foreach_pair_component_in_list
			 (xtraexp)
			 (xtrapair curxtra)
			 (list_append expreslist curxtra)
			 ))
		       (xtraexp
			(list_append expreslist xtraexp))
		       )
		      )
		     )
		   )
		  (let ( (restup (list_to_multiple expreslist discr_multiple))
			 )
		    (debug "expand_tuple_slice_as_tuple result=" restup)
		    (return restup)
		    )))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun register_generator_device (defin repr modctx)
  :doc #{Function to register some C generating device in the module
  context, to be able to generate for syntax correctness a dummy
  syntax-testing C function.}# 
  (debug "register_generator_device defin=" defin 
	 "\n* repr=" repr "\n* modctx=" modctx "\n")
  (assert_msg "check defin" (is_a defin class_source_definition) defin)
  (assert_msg "check repr" (is_object repr) repr)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (is_a modctx class_any_module_context)
      (let ( (sloc (get_field :loca_location defin))
	     (mgendevlist (get_field :mocx_gendevlist modctx))
	     (gendev (instance class_source_generator_device
			       :loca_location sloc
			       :srcgen_defin defin
			       :srcgen_repr repr))
	     )
	(list_append mgendevlist gendev)
	(debug "register_generator_device gendev=" gendev 
	       "\n* updated mgendevlist=" mgendevlist)
	)))



;;; expand an s-expression known to be an application
(defun expand_apply (sexpr env mexpander modctx)
  (debug "expand_apply" " sexpr=" sexpr " env=" debug_less env)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (soper (pair_head (list_first scont)))
	 (xargtup (expand_restlist_as_tuple scont env mexpander modctx))
	 (xoper (if (is_a soper class_sexpr) 
		    (mexpander soper env mexpander modctx) 
		  soper))
	 )
    (instance class_source_apply
	      :loca_location sloc
	      :sapp_fun xoper
	      :sargop_args xargtup)))


;;; expand an s-expression known to be a message send
(defun expand_msend  (opnam sexpr env mexpander modctx)
  (debug "expand_msend sexpr=" sexpr "\n.. env=" debug_less env)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check opnam" (is_a opnam class_symbol) opnam)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (spair (pair_tail (list_first scont)))
	 )
    (if (not (is_pair spair))
	(error_at sloc "missing receiver expression in message passing"_))
    (let ( (xrecv (pair_head spair))
	   (argtup (expand_pairlist_as_tuple (pair_tail spair) env mexpander modctx)) 
	   (res (instance class_source_msend
			  :loca_location sloc
			  :msend_selsymb opnam
			  :msend_recv (if (is_a xrecv class_sexpr)
					  (mexpander xrecv env mexpander modctx)
					xrecv)
			  :sargop_args argtup
			  ))
	   )
      (debug "expand_msend res" res)
      res
      )))



;;; expand an s-expression known to be a safe field access
(defun expand_fieldexpr (fld sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check fld" (is_a fld class_field) fld)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (debug "expand_fieldexpr sexpr" sexpr)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 )
;;;;;;;; this don't work yet on january 25th 2011 svn rev 169278!
;;;;;;;;  ERRORed: unimplemented scan_pattern for pattern  - CLASS_SOURCE_PATTERN_LIST
    ;;     (match scont
    ;; 	   (?(list ?(and ?flnam ?(instance class_keyword))
    ;; 		   ?subexpr)
    ;; 	     (let (
    ;; 		   (mexp (mexpander subexpr env mexpander modctx))
    ;; 		   (res (instance class_source_get_field
    ;; 				  :loca_location sloc
    ;; 				  :suget_obj mexp
    ;; 				  :suget_field fld))
    ;; 		   )
    ;; 	       (debug "expand_fieldexpr result" res)
    ;; 	       (return res)
    ;; 	     ))
    ;; 	   (?_
    ;; 	    (error_plain sloc "bad field expression - expecting (:fieldname <expr>)")
    ;; 	    (return))
    ;; 	   )
    (let ( (scontup (list_to_multiple scont discr_multiple))
	   (operexp (multiple_nth scontup 0))
	   (subsexp (multiple_nth scontup 1))
	   )
      (debug "expand_fieldexpr scontup" scontup)
      (if (!=i (list_length scont) 2)
	  (progn
	    (error_at sloc "expecting one argument in (:field <subexpr>)")
	    (return)))
      (assert_msg "check operexp" (is_a operexp class_keyword) operexp)
      (assert_msg "same operexp as field"
		  (==s (get_field :named_name fld) (get_field :named_name operexp))
		  operexp fld)
      (let ( 
	    (mexp (mexpander subsexp env mexpander modctx))
	    (res (instance class_source_get_field
			   :loca_location sloc
			   :suget_obj mexp
			   :suget_field fld))
	    )
	(debug "expand_fieldexpr result" res)
	(return res)
	))))



    

;; every citeration is (symbol (startargs) (varformals) body...)
;; expand an s-expression known to be a citeration
(defun expand_citeration (citer sexpr env mexpander modctx)
  (debug "expand_citeration sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check citer" (is_a citer class_citerator) citer)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (spair (pair_tail (list_first scont)))
	 (stargs ())		;set to the tuple of start expressions
	 (varformals ())	;set to the varformals binding tuple
	 (bodytup ())		;set to the body tuple
	 (newenv (fresh_env env))
	 )
    ;; parse the startargs
    (if  (is_pair spair)
	(let ( (starexp (pair_head spair)) )
	  (if (is_a starexp class_sexpr)
	      (let ( (stacont (unsafe_get_field :sexp_contents starexp))
		     )
		(setq stargs (expand_pairlist_as_tuple (list_first stacont) env mexpander modctx))
		)
	    (setq stargs (if starexp (tuple
				      (mexpander starexp env mexpander modctx)
				      ))))
	  (setq spair (pair_tail spair))
	  )
      (progn
	(error_at sloc "missing startargs expression in citeration $1"_
		    (unsafe_get_field :named_name citer))
	(return)
	))
    ;; parse the varformals and bind them in the newenv
    (if  (is_pair spair)
	(let ( (varexp (pair_head spair)) )
	  (setq spair (pair_tail spair))
	  (setq varformals (lambda_arg_bindings varexp () env mexpander modctx))
	  )
      (progn
	(error_at sloc "missing varformals in citeration $1"_
		    (unsafe_get_field :named_name citer))
	(return)
	))
    (foreach_in_multiple 
     (varformals)
     (lb :long lix) (put_env newenv lb))
    ;; parse the body in the new environment
    (setq bodytup (expand_pairlist_as_tuple spair newenv mexpander modctx))
    ;; build & return the result
    (let ( (sciter (instance class_source_citeration
			     :loca_location sloc
			     :sciter_oper citer
			     :sargop_args stargs
			     :sciter_varbind varformals
			     :sciter_body bodytup))
	   )
      (debug "expand_citeration result sciter" sciter)
      (return sciter)
      )))


;; expand a cmatcher expression
;;; this is for cmatcher in expression contexts (not as patterns!)
(defun expand_cmatchexpr (cmat sexpr env mexpander modctx)
  (debug "expand_cmatchexpr sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check cmat" (is_a cmat class_cmatcher) cmat)
  (assert_msg "check modctx" (is_object modctx))
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (spair (pair_tail (list_first scont)))
	 (soper (pair_head (list_first scont)))
	 (xargtup (expand_restlist_as_tuple scont env mexpander modctx))
	 (cmatin (get_field :amatch_in cmat))
	 (cmatout (get_field :amatch_out cmat))
	 (cmatexp (get_field :cmatch_expoper cmat))
	 (cmatname (get_field :named_name cmat))
	 (:long nbxargs (multiple_length xargtup))
	 (:long nbouts (multiple_length cmatout))
	 )
    (debug "expand_cmatchexpr xargtup=" xargtup "\n cmatin=" cmatin
	   "\n cmatout=" cmatout
	   "\n cmat=" cmat)
    (when (!=i nbxargs nbouts)
	  (debug "expand_cmatchexpr bad xargtup=" xargtup
		 "\n bad cmatin=" cmatin
		 "\n bad cmatout=" cmatout)
	  (error_at sloc
			"bad argument number $1 for cmatcher $2 expression wanting $3 outputs"_
			nbxargs cmatname nbouts))
    (when (null cmatexp)
      (error_at sloc
		      "cmatcher $1 used without operation expansion"_
		      cmatname)
	  (return))
    ;; should build a class_source_cmatchexpr
    (let ( (res
	    (instance class_source_cmatchexpr
		      :loca_location sloc
		      :scmatx_cmatcher cmat
		      :sargop_args xargtup)
	    ) )
      (debug "expand_cmatchexpr res" res)
      (return res)
      )))


;;; expand a funmatcher expression
;;;; this is for funmatcher in expression contexts (not as patterns) 
(defun expand_funmatchexpr (fmat sexpr env mexpander opbind modctx)
  (debug "expand_funmatchexpr sexpr=" sexpr " fmat=" fmat)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check fmat" (is_a fmat class_funmatcher) fmat)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (spair (pair_tail (list_first scont)))
	 (soper (pair_head (list_first scont)))
	 (xargtup (expand_restlist_as_tuple scont env mexpander))
	 (fmatapp (unsafe_get_field :fmatch_applyf fmat))
	 )
    (debug "expand_funmatchexpr xargtup" xargtup)
    (debug "expand_funmatchexpr fmatapp" fmatapp)
    (debug "expand_funmatchexpr opbind" opbind)
    ;; we need to build a specific funmatchexpr, because it is handled
    ;; differently from a simple application
    (let ( (res (instance class_source_funmatchexpr
			  :loca_location sloc
			  :sfmatx_fmatcher fmat
			  :sfmatx_fmatbind opbind
			  :sargop_args xargtup)) )
      (debug "funmatcher result" res)
      (return res)
    )))


;;; expand a keywordfun s-expression
;;; handle stuff like
;;;;; (:fieldname obj) to get a field
(defun expand_keywordfun (soper sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (debug "expand_keywordfun sexpr" sexpr)
  (debug "expand_keywordfun soper" soper)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (tupcont (list_to_multiple scont discr_multiple))
	 )
    (error_at sloc "expand_keywordfun not implemented"_)
    (assert_msg "@@@  expand_keywordfun NOT IMPLEMENTED" () soper sexpr)
    )
  )



;;;;;;;;;;;;;;;; the main macro expander of one expression
(defun macroexpand_1 (sexpr env mexpander modctx)
  :doc #{Function to macro-expand a single s-expr $SEXPR in
  environment $ENV using the macroexpander $MEXPAND in module context
  $MODCTX. Return the expanded form, subclass of $CLASS_SOURCE, and
  perhaps other such source expansions in a list or tuple secondary
  result.}#
  (debug "macroexpand_1 sexpr=" sexpr "\n.. env=" debug_less env)
  (shortbacktrace_dbg "macroexpand_1" 15)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (is_a sexpr class_sexpr)
      (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	     (sloc (unsafe_get_field :loca_location sexpr))
	     (soper (pair_head (list_first scont))) )
	(debug "macroexpand_1 sexpr=" sexpr "\n.. soper" soper)
	(if (melt_call_deeper_than 64)
	    (warning_plain sloc "MELT quite deep macro expansion"))
	(cond 
;;;; first test for keywords, since they are also symbols
	 ( (is_a soper class_keyword)
	   (let ( (resk (expand_keywordfun soper sexpr env mexpander)) )
	     (debug "macroexpand_1 result for keywordfun resk" resk)
	     (return resk ())))
;;;; test for non-keyword symbols...
	 ( (is_a soper class_symbol)
	   (let ( (opbind (find_env env soper)) 
		  (opname (get_field :named_name soper))
		  )
	     (debug "macroexpand_1 opbind=" opbind "; for sloc=" debug_less sloc
		    "\n.. for soper=" soper)
	     (cond ( (is_a opbind class_macro_binding)
		     (let ( (mexp (unsafe_get_field :mbind_expanser opbind)) 
			    )
		       (shortbacktrace_dbg "macroexpand_1 macrobinding" 10)
		       (when (null mexp)
			 (error_at sloc "macro $1 cannot be expanded since not yet defined"_ opname)
			 (return () ()))
		       (debug "macroexpand_1 mexp=" mexp "\n.. sexpr=" sexpr "\n.. env=" debug_less env)
		       (assert_msg "check mexp" (is_closure mexp) mexp)
		       (multicall 
			(resm otherm)
			(mexp sexpr env mexpander modctx)
			(debug "macroexpand_1 result for macro resm=" resm "\n.. otherm=" otherm)
			(cppif MELT_HAVE_DEBUG
			       (if (null resm)
				   (debug "macroexpand_1 null result for macro sexpr=" sexpr)))
			 (return resm otherm)
			 )))
		   ( (is_a opbind class_selector_binding)
		     (let ( (ress (expand_msend soper sexpr env mexpander modctx)) )
		       (debug "macroexpand_1 result for send ress" ress)
		       (return ress ())
		       ))
		   ( (is_a opbind class_primitive_binding)
		     (let ( (resp (expand_primitive (unsafe_get_field :pbind_primitive opbind) 
						    sexpr env mexpander modctx)) )
		       (debug "macroexpand_1 result for primitive resp" resp)
		       (return resp ())
		       ))
		   ( (is_a opbind class_citerator_binding)
		     (let ( (citer (unsafe_get_field :cbind_citerator opbind))
			    (resc (expand_citeration citer sexpr env mexpander modctx))
			    )
		       (debug "macroexpand_1 result for citerator resc=" resc)
		       (return resc ())
		       ))
		   ( (is_a opbind class_hook_binding)
		     (let ( (hookdef (unsafe_get_field :hookbind_defhook opbind))
			    (resc (expand_hook hookdef sexpr env mexpander modctx))
			    )
		       (debug "macroexpand_1 result for hook resc=" resc)
		       (return resc ())
		       ))
		   ( (is_a opbind class_cmatcher_binding)
		     (let ( (cmatch (unsafe_get_field :cmbind_matcher opbind))
			    (resc (expand_cmatchexpr cmatch sexpr env mexpander modctx))
			    )
		       (debug "macroexpand_1 result for cmatcher resc" resc)
		       (return resc ())
		       ))
		   ( (is_a opbind class_funmatcher_binding)
		     (let ( (fmatch (unsafe_get_field :fmbind_funmatcher opbind)) 
			    (resf (expand_funmatchexpr fmatch sexpr env mexpander opbind modctx))
			    )
		       (debug "macroexpand_1 result for funmatcher resf" resf)
		       (return resf ())
		       ))
		   ( (is_a opbind class_field_binding)
		     (let ( (field (unsafe_get_field :flbind_field opbind)) 
			    (resf (expand_fieldexpr field sexpr env mexpander modctx))
			    )
		       (debug "macroexpand_1 result for field resf" resf)
		       (return resf ())
		       ))
		   ;; formals and local variables are always applied.
		   ( (is_a opbind class_formal_binding)
		     (return (expand_apply sexpr env mexpander modctx) ()))
		   ( (is_a opbind class_let_binding)
		     (return (expand_apply sexpr env mexpander modctx) ()))
;;; [imported] value bindings are handled case by case
		   ( (is_a opbind class_value_binding)
		     (let ( (val (unsafe_get_field :vbind_value opbind))
			    )
		       (cond
			( (is_closure val)
			  (return (expand_apply sexpr env mexpander modctx) ())
			  )
			( (is_a val class_primitive)
			  (return (expand_primitive val sexpr env mexpander modctx) ())
			  )
			( (is_hook val)
			  (return (expand_hook val sexpr env mexpander modctx) ())
			  )
			( (is_a val class_selector) 
			  (let ( (ress 
				  (expand_msend soper sexpr env mexpander modctx)) )
			    (debug "macroexpand_1 result for send ress" ress)
			    (return ress ())
			    )
			  )
			( (is_a val class_citerator)
			  (let ( (resc 
				  (expand_citeration val sexpr env mexpander modctx)) )
			    (debug "macroexpand_1 result for send resc" resc)
			    (return resc ())))
			( (is_a val class_cmatcher)
			  (let ( (resc
				  (expand_cmatchexpr val sexpr env mexpander modctx)) )
			    (debug "macroexpand_1 result for cmatch resc" resc)
			    (return resc ())))
			( (is_a val class_funmatcher)
			  (let ( (resf (expand_funmatchexpr val sexpr env mexpander opbind modctx)) )
			    (debug "macroexpand_1 result for funmatch resf" resf)
			    (return resf ())))
			( (is_a val class_field)
			  (let ( (resf (expand_fieldexpr val sexpr env mexpander modctx)) )
			    (debug "macroexpand_1 result for field resf" resf)
			    (return resf ())))
			(:else
			 (error_at sloc "macroexpand_1 bad valued operation symbol $1"_
				     (unsafe_get_field :named_name soper))
			 (inform_strv sloc "macroexpand_1 bad symbol value discr"
				      (unsafe_get_field :named_name (discrim val)))
			 (return () ())
			 )
			))) ;; end if opbind is a value binding
		   ( (and 
		      (null opbind)
		      (not (melt_is_bootstrapping))
		      )
		     (debug "macroexpand_1 null opbind for soper=" soper
			    "; sloc=" sloc
			    "\n.. sexpr=" sexpr
			    "\n.. env=" debug_more env)
		     (shortbacktrace_dbg "macroexpand_1 nullopbind" 15)
		     (let ( (macthunk (lambda ()
					(debug "macroexpand_1 macthunk sloc=" sloc)
					(shortbacktrace_dbg "macroexpand_1 macthunk" 15)
					(mexpander sexpr env mexpander modctx)
					))
			    (lazymac (instance class_source_lazy_macro_expansion
					       :loca_location sloc
					       :slazymacro_fun macthunk
					       :slazymacro_oper soper
					       ))
			    )
		       (debug "macroexpand_1 return lazymac" lazymac
			      "\n.. for sexpr=" debug_less sexpr
			      "\n.. in env=" env)
		       (shortbacktrace_dbg "macroexpand_1 lazymac" 15)
		       (return lazymac ())
		       ))
		   (:else 
		    (if (and 
			 (melt_is_bootstrapping)
			 (null opbind))
			(warning_strv
			 sloc 
			 "forward referenced operator handled as application when bootstrapping MELT"
			 (get_field :named_name soper)
			 ))
		    ;; if opbind is null, we should expand to a class_source_lazy_macro_expansion
		    (let ( (resa (expand_apply sexpr env mexpander modctx))) 
		      (debug "macroexpand_1 result for apply resa" resa)
		      (return resa ())
		      )
		    ))))
	 ;; the empty list is expanded as nil
	 ( (==i (list_length scont) 0)
	   (debug "macroexpand_1 result for null")
	   (return () ()))
	 (:else 
	  (let ( (resca (expand_apply sexpr env mexpander modctx)) )
	    (debug "macroexpand_1 result complex apply resca" resca)
	    (return resca ())
	    ))))
    ;; if the sexpr is not an sexpr return itself
    (progn 
      (debug "macroexpand_1 non-sexpr result sexpr=" sexpr)
      (return sexpr ()))))

;;;;;;;;;;;;;;;;
;;; expand a primitive s-expression
(defun expand_primitive (sprim sexpr env mexpander modctx)
  (assert_msg "check sprim" (is_a sprim class_primitive) sprim)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (soper (pair_head (list_first scont)))
	 (xargtup (expand_restlist_as_tuple scont env mexpander modctx))
	 )
    (instance class_source_primitive
	      :loca_location sloc
	      :sprim_oper sprim
	      :sargop_args xargtup)))

;;; expand a hook s-expression
(defun expand_hook (shook sexpr env mexpander modctx)
  (debug "expand_hook shook=" shook " sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (assert_msg "check shook" (or (is_hook shook) (is_a shook class_source_defhook)) shook)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (soper (pair_head (list_first scont)))
	 (xargtup (expand_restlist_as_tuple scont env mexpander modctx))
	 (resh (instance class_source_hook_call
			 :loca_location sloc
			 :sargop_args xargtup
			 :shook_called shook
			 ))
	 )
    (debug "expand_hook gives resh=" resh)
    (return resh ())
))

;;; class for pattern expansion context
(defclass class_pattern_expansion_context
  :doc #{The internal $CLASS_PATTERN_EXPANSION_CONTEXT is for
expansion of patterns. $PCTX_MEXPANDER is the macroexpander for
expressions, $PCTX_PEXANDER is the pattern expander, $PCTX_VARMAP is
the object-map for pattern variables. $PCTX_MODCTX is the module context.}#
  :super class_root
  :fields (pctx_mexpander      	;macroexpander
	   pctx_pexpander      	;pattern expander
	   pctx_varmap	        ;objmap for pattern variables [symbols => srcpattern_variable]
	   pctx_modctx		;module context
	   ))


(defun patternexpand_pairlist_as_tuple (pairlist env pctx psloc)
  (debug "patternexpand_pairlist_as_tuple pairlist" pairlist)
  (let ( (restup (pairlist_to_multiple 
		  pairlist discr_multiple
		  (lambda (x) (patternexpand_1 x env pctx psloc))))
	 )
    (debug "patternexpand_pairlist_as_tuple return restup" restup)
    (return restup)
    ))


;; utility function to expand a pairlist for a pattern matcher with both input & output arguments
;; the primary result is the tuple of argexpr
;; the secondary result is the tuple of subpatterns
(defun patmacexpand_for_matcher (pairs matcher env psloc pctx)
  (assert_msg "check matcher" (is_a matcher class_any_matcher) matcher)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (let ( (mins (unsafe_get_field :amatch_in matcher))
	 (mouts (unsafe_get_field :amatch_out matcher))
	 (mexpander (unsafe_get_field :pctx_mexpander pctx))
	 (modctx (get_field :pctx_modctx pctx))
	 (matname (get_field :named_name matcher))
	 (:long nbmins (multiple_length mins))
	 (:long nbouts (multiple_length mouts))
	 (paircont (instance class_reference :referenced_value pairs))
	 (inargs (multiple_map 
		  mins
		  (lambda (curfbind :long inix)
		    (assert_msg "check curfbind" (is_a curfbind class_formal_binding) curfbind)
		    (let ( (curpair (get_field :referenced_value paircont)) )
		      (if (is_pair curpair)
			  (let ( (curin (pair_head curpair)) )
			    (put_fields paircont :referenced_value (pair_tail curpair))
			    (mexpander curin env mexpander modctx))
			(error_at psloc "missing input argument #$1 for matcher $2"
				    inix matname)
			)))))
	 (outpats (multiple_map
		   mouts 
		   (lambda (curformal :long outix)
		     (let ( (curpair (get_field :referenced_value paircont)) )
		       (if (is_pair curpair)
			   (let ( (curout (pair_head curpair)) )
			     (put_fields paircont :referenced_value (pair_tail curpair))
			     (patternexpand_1 curout env pctx psloc))
			 (error_at psloc "missing output argument #$1 for matcher $2"
				     outix matname)
			 )))))
	 )
    (let ( (curpair (get_field :referenced_value paircont)) )
      (when (is_pair curpair)
	    (debug "extra stuff in patmacexpand_for_matcher" curpair)
	    (error_at psloc "ignored extra sub-{pattern | expression} in matcher"
			matname)))
    (return inargs outpats)
    ))

(defun pattern_weight_tuple (spats)
  :doc #{The function $PATTERN_WEIGHT_TUPLE compute the tuple, and
  their maximum, their minimum, and their sum, of the pattern weights of
  the $SPATS tuple argument made of instances of
  $CLASS_SOURCE_PATTERN.}#
  (assert_msg "check spats" (is_multiple spats) spats)
  (let
      ( (bsum (make_integerbox discr_integer 0))
	(bmax (make_integerbox discr_integer 0))
	(bmin (make_integerbox discr_integer 0))
	(restup
	 (multiple_map 
	  spats
	  (lambda (subpat :long subix)
	    (let ( (boxsubw (get_field :pat_weight subpat))
		   (:long subw (get_int boxsubw))
		   (:long isum (get_int bsum))
		   (:long imin (get_int bmin))
		   (:long imax (get_int bmax))
		   )
	      (if subw
		  (progn 
		    (setq isum (+i isum subw))
		    (setq imin (mini imin subw))
		    (setq imax (maxi imax subw))
		    (put_int bsum isum)
		    (put_int bmin imin)
		    (put_int bmax imax)
		    (return (make_integerbox discr_constant_integer subw))))))))
	)
    (return restup (get_int bmax) (get_int bmin) (get_int bsum))))


;; pattern expansion of a pattern expression like (question SEXPR)
(defun patternexpand_expr (sexpr env pctx psloc)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (debug "patternexpand_expr sexpr" sexpr)
  (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	 (sloc (unsafe_get_field :loca_location sexpr))
	 (curpair (list_first scont))
	 (soper (pair_head curpair)) )
    (when (is_not_a soper class_symbol)
	  (debug "patternexpand_expr bad soper" soper)
	  (error_at sloc "pattern expression requires symbol operator")
	  (return))
    (let ( (opbind (find_env env soper))
	   (opnam (unsafe_get_field :named_name soper))
	   )
      (debug "patternexpand_expr opbind" opbind)
      (cond 
       ( (null opbind)
	 (error_at sloc "unbound pattern operator $1" opnam)
	 )
       ( (is_a opbind class_patmacro_binding)
	 (let ( (patexp (unsafe_get_field :patbind_expanser opbind)) )
	   (assert_msg "check patexp" (is_closure patexp) patexp)
	   (let ( (resp (patexp sexpr env pctx)) )
	     (debug "patternexpand_expr patmacro so return resp" resp)
	     (return resp)
	     )))
       ( (is_a opbind class_cmatcher_binding)
	 (let ( (cmat (unsafe_get_field :cmbind_matcher opbind)) )
	   (debug "patternexpand_expr cmat" cmat)
	   (assert_msg "check cmat-cher" (is_a cmat class_cmatcher) cmat)
	   (multicall
	    (args pats)
	    (patmacexpand_for_matcher (pair_tail curpair) cmat env sloc pctx)
	    (debug "patternexpand_expr cmatcher args" args)
	    (debug "patternexpand_expr cmatcher pats" pats)
	    (multicall
	     (subpatw :long imax imin isum)
	     (pattern_weight_tuple pats)
	     (let ( (pcomp (instance class_source_pattern_c_match
				     :loca_location sloc
				     :pat_weight 
				     (make_integerbox discr_constant_integer (+i 1 isum))
				     :spac_operator cmat
				     :spac_operbind opbind
				     :spac_inargs args
				     :spac_outargs pats
				     ))
		    )
	       (debug "patternexpand_expr cmatcher return pcomp" pcomp)
	       (return pcomp)
	       )))))
       ;; funmatcher binding
       ( (is_a opbind class_funmatcher_binding)
	 (let ( (fmat (unsafe_get_field :fmbind_funmatcher opbind)) 
		(defm (unsafe_get_field :fmbind_defunmatcher opbind))
		)
	   (debug "patternexpand_expr funmatcher fmat" fmat)
	   (debug "patternexpand_expr funmatcher defm" defm)
	   (debug "patternexpand_expr funmatcher opbind" opbind)
	   (assert_msg "check fmat-cher" (is_a fmat class_funmatcher) fmat)
	   (multicall
	    (args pats)
	    (patmacexpand_for_matcher (pair_tail curpair) fmat env sloc pctx)
	    (debug "patternexpand_expr funmatcher args" args)
	    (debug "patternexpand_expr funmatcher pats" pats)
	    (multicall
	     (subpatw :long imax imin isum)
	     (pattern_weight_tuple pats)
	     (let ( (pcomp (instance class_source_pattern_fun_match
				     :loca_location sloc
				     :pat_weight 
				     (make_integerbox discr_constant_integer (+i 1 isum))
				     :spac_operator fmat
				     :spac_operbind opbind
				     :spac_inargs args
				     :spac_outargs pats
				     )) )
	       (debug "patternexpand_expr funmatcher return pcomp" pcomp)
	       (return pcomp)
	       )))))
       ;; imported values 
       ( (is_a opbind class_value_binding)
	 (let ( (opval (unsafe_get_field :vbind_value opbind)) )
	   (debug "patternexpand_expr imported opval" opval)
	   (cond 
	    ( (is_a opval class_cmatcher) 
	      (multicall
	       (args pats)
	       (patmacexpand_for_matcher (pair_tail curpair) opval env sloc pctx)
	       (debug "patternexpand_expr imported cmatcher args" args)
	       (debug "patternexpand_expr imported cmatcher pats" pats)
	       (multicall
		(subpatw :long imax imin isum)
		(pattern_weight_tuple pats)
		(let ( (pcomp (instance class_source_pattern_c_match
					:loca_location sloc
					:pat_weight 
					(make_integerbox discr_constant_integer (+i 1 isum))
					:spac_operator opval
					:spac_operbind opbind
					:spac_inargs args
					:spac_outargs pats
					))
		       (aouts (get_field :amatch_out opval))
		       )
		  (debug "patternexpand_expr imported cmatcher pats again" pats)
		  (debug "patternexpand_expr aouts" aouts)
		  (if (!=i (multiple_length pats) (multiple_length aouts))
		      (warning_at sloc "incompatible number of formal and actual subpatterns of cmatcher $1"
				    (get_field :named_name opval)))
		  (debug "patternexpand_expr cmatcher value pcomp" pcomp)
		  (return pcomp)
		  ))))
	    ( (is_a opval class_funmatcher) 
	      (debug "patternexpand_expr funmatcher value opval" opval)
	      (multicall
	       (args pats)
	       (patmacexpand_for_matcher (pair_tail curpair) opval env sloc pctx)
	       (debug "patternexpand_expr imported funmatcher args" args)
	       (debug "patternexpand_expr imported funmatcher pats" pats)
	       (multicall
		(subpatw :long imax imin isum)
		(pattern_weight_tuple pats)
		(let ( (pcomp (instance class_source_pattern_fun_match
					:loca_location sloc
					:pat_weight
					(make_integerbox discr_constant_integer (+i 1 isum))
					:spac_operator opval
					:spac_operbind opbind
					:spac_inargs args
					:spac_outargs pats
					))
		       )
		  (debug "patternexpand_expr funmatcher value pcomp" pcomp)
		  (return pcomp)
		  ))
	       ))
	    (:else
	     (error_at sloc "invalid pattern operator $1 value" opnam)
	     (return)))))
       (:else
	(error_at sloc
		    "pattern operator $1 badly bound - patternmacro expected"
		    opnam)
	)
       )
      ))
  )

;; pattern expansion
(defun patternexpand_1 (sexpr env pctx psloc)
  (debug "patternexpand_1 start sexpr=" sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (cond
   ( (is_a sexpr class_sexpr)
     (let ( (scont (unsafe_get_field :sexp_contents sexpr))
	    (sloc (unsafe_get_field :loca_location sexpr))
	    (modctx (get_field :pctx_modctx pctx))
	    (curpair (list_first scont))
	    (soper (pair_head curpair)) )
       (debug "patternexpand_1 sexpr" sexpr)
       (debug "patternexpand_1 soper" soper)
       (if (!= soper 'question)
	   ;; non-question expr: return the constant pattern with...
	   (let ( (mexpander (unsafe_get_field :pctx_mexpander pctx)) 
		  (exp (mexpander sexpr env mexpander modctx))
		  (pat (instance class_source_pattern_constant
				 :loca_location sloc
				 :pat_weight '1
				 :spat_constx exp))
		  )
	     (debug "patternexpand_1 return const pat" pat)
	     (return pat)
	     )
	 ;; question expr
	 (let ( (parg1 (pair_head (setq curpair (pair_tail curpair)))) )
	   (if (pair_tail curpair)
	       (error_at sloc "QUESTION should have one argument"))
	   (cond
	    ((== parg1 '_)		;  ?_ is a joker
	     (let ( (jokp (instance class_source_pattern_joker_variable
				    :loca_location sloc
				    :pat_weight '1
				    :spatvar_symb parg1
				    :spatvar_nbocc (make_integerbox discr_integer 0)
				    )) )
	       (debug "patternexpand_1 return jokervar" jokp)
	       (return jokp)
	       ))
	    ((is_a parg1 class_symbol)
	     ;; if parg1 is a symbol, make a patternvariable and add it
	     ;; into pctx
	     (let ( (vamp (unsafe_get_field :pctx_varmap pctx))
		    (pavr (mapobject_get vamp parg1))
		    )
	       (if pavr 
		   (progn
		     (debug "patternexpand_1 return found pavr" pavr)
		     (return pavr)
		     )
		 (let ( (newpavr (instance class_source_pattern_variable
					   :pat_weight '1
					   :loca_location sloc
					   :spatvar_symb parg1
					   :spatvar_nbocc (make_integerbox discr_integer 0)
					   )) 
			)
		   (mapobject_put vamp parg1 newpavr)
		   (debug "patternexpand_1 return nexpavr" newpavr)
		   (return newpavr))
		 ))
	     )
	    ((is_a parg1 class_sexpr)
	     (debug "patternexpand_1 sexpr parg1=" parg1)
	     (let ( (patex (patternexpand_expr parg1 env pctx sloc)) )
	       (debug "patternexpand_1 return patex" patex)
	       (return patex))
	     )
	    (:else
	     (error_at sloc "unexpected pattern QUESTION - neither symbol nor pattern expr")))
	   )
	 ))
     )
   (:else
    ;; not an s-expr, return the constant pattern with...
    (let ( (mexpander (unsafe_get_field :pctx_mexpander pctx)) 
	   (pat (instance class_source_pattern_constant
			  :pat_weight '1
			  :loca_location psloc
			  :spat_constx sexpr))
	   )
      (debug "patternexpand_1 return const pat as source" pat)
      (return pat)
      ))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; we add an additional hack in toplevel macro-expansion. If an s-expr
;; macroexpands to a tuple or a list, that tuple is handled as several source
;; expressions... In particular, this allows a (load "filename")
;; macro.
(defun macroexpand_toplevel_list (slist env mexpander modctx)
  
  :doc #{The $MACRO_EXPAND_TOPLEVEL_LIST is macro-expanding a list
  $SLIST of top-level S-expressions, in environment $ENV, using the
  macro-expanded $MEXPANDER, in module context $MODCTX. Any such
  top-level S-expressions macroexpanded to nil is silently skipped,
  like $SKIP_NIL does.}#
  (debug "macroexpand_toplevel_list slist=" slist 
	 "\n* mexpander=" mexpander
	 "\n* modctx=" modctx)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check slist" (is_list slist) slist)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (:long slistlen (list_length slist)) 
	 (reslist (make_list discr_list)) 
	 (prevloc ())
	 )
    ;;
    ;;
    (foreach_pair_component_in_list
     (slist)
     (curpair sexp)
     (debug "macroexpand_toplevel_list sexp=" sexp)
     ;; When a simple literal or symbol appears erronously at the
     ;; toplevel, we have no location to make the error, so we issue a
     ;; warning for the *previous* s-expression!
     (if (is_a sexp class_located)
	 (let ( (sexploc (unsafe_get_field :loca_location sexp)) )
	   (if sexploc (setq prevloc sexploc)))
       (warning_plain prevloc
		      "Top-level s-expression followed by an unexpected atom"))
     (debug "macroexpand_toplevel_list prevloc=" debug_less prevloc "; sexp=" sexp 
	    "\n... env=" env "\n")
     ;;
     (let ( (sexploc (get_field :loca_location sexp))
	    )
       (multicall
	(mex mxtra)
	(mexpander sexp env mexpander modctx)
	(debug "macroexpand_toplevel_list sexploc=" debug_less sexploc
	       "; mex=" mex "\n.. mxtra=" mxtra)
	;; process the primary result
	(cond
	 ( (null mex)
	   ;; if an S-expression at top level is expanded to nil, that
	   ;; nil is *not* considered.
	   (void)
	   )
	 ( (is_multiple mex)
	   (foreach_in_multiple
	    (mex)
	    (curm :long curix)
	    (list_append reslist curm))
	   )
	 ( (is_list mex)
	   (list_append2list reslist mex))
	 (:else (list_append reslist mex)
		))
	;; handle the secondary result
	(cond
	 ( (null mex)
	   ;; special case, if the primary result of top-level
	   ;; expansion is nil, any secondary result is ignored.
	   (void)
	   )
	 ( (null mxtra)
	   (void))
	 ( (is_multiple mxtra)
	   (foreach_in_multiple
	    (mxtra)
	    (curm :long curix)
	    (list_append reslist curm))
	   )
	 ( (is_list mxtra)
	   (list_append2list reslist mxtra)
	   )
	 (:else
	  (list_append reslist mxtra)))
	))
     )				   ;end foreach_pair_component_in_list
    (debug "macroexpand_toplevel_list reslist=" reslist)
    (let ( (:long reslistlen (list_length reslist))
	   )
      (if (or (<i reslistlen slistlen)
	      (<i reslistlen 2))
	  (code_chunk warnshortreschk
		      #{/*$WARNSHORTRESCHK*/
		      warning(0, "MELT expanded list of %ld s-expressions into short list of %ld source elements",
				 $SLISTLEN, $RESLISTLEN) ;
		      }#))
      )
    (return reslist)
    )
  )


;;; expand an s-expression into a tuple of formal bindings
;;; the formalsexp is the sexpr of formals 
;;; the [optional] argmode should be set :checkargs to check arguments type
;;; usually argmode is just missing
;;; TODO: perhaps consider a :macro argmode also??
(defun lambda_arg_bindings (formalsexp argmode env mexpander modctx)
  ;; special case for null arglist
  (when (null formalsexp)
    (return (make_multiple discr_formal_sequence 0)))
  (assert_msg "check formalsexp" (is_a formalsexp class_sexpr) formalsexp)
  (let ( (:long argrk 0)
	 (argtype ctype_value)
	 (rawarglist (unsafe_get_field :sexp_contents formalsexp))
	 (argloc (unsafe_get_field :loca_location formalsexp))
	 (arglist (expand_pairlist_as_list (list_first rawarglist) env mexpander modctx))
	 (argmap (make_mapobject discr_map_objects (+i 4 (list_length arglist))))
	 (bndlist (make_list discr_list)) 
	 (curpair (list_first arglist))
	 (tupdis discr_formal_sequence)
	 )
    ;; first loop on arg
    (forever argloop
	     (if (null curpair) (exit argloop))
	     (assert_msg "check curpair" (is_pair curpair) curpair)
	     (let ( (curarg (pair_head curpair)) )
	       (cond
		( (== curarg :rest)
		  (setq curpair (pair_tail curpair))
		  (when curpair
		    (error_at argloc ":REST should be last in variadic formals")
		    (return))
		  (setq tupdis discr_variadic_formal_sequence)
		  (void)
		  )
		( (== curarg :auto)
		  (error_at argloc ":AUTO is not permitted in formal arguments")
		  (setq curpair (pair_tail curpair))
		  (void)
		  )
		( (is_a curarg class_keyword)
		  (let ( (cty (unsafe_get_field :symb_data curarg)) 
			 (curargname (unsafe_get_field :named_name curarg))
			 )
		    (cond 
		     ( (is_not_a cty class_ctype)
		       (error_at argloc "non-ctype keyword $1 in formal arglist"_
				 curargname))
		     ( (== (unsafe_get_field :ctype_keyword cty) curarg)
		       (setq argtype cty))
		     ( (== (unsafe_get_field :ctype_altkeyword cty) curarg)
		       (warning_strv argloc "usage of alternate keyword as formal's ctype is deprecated"
				     curargname)
		       (inform_strv argloc "prefered ctype keyword is"
				    (get_field :named_name (get_field :ctype_keyword cty)))
		       (setq argtype cty))
		     (:else
		      (error_at argloc "invalid keyword $1 in formal arglist"_
				(unsafe_get_field :named_name curarg))
		      ())
		     )
		    )
		  (void)
		  )
		( (is_a curarg class_symbol)
		  (if (mapobject_get argmap curarg)
		      (error_at argloc "duplicate argument $1 in formal arglist"_
				(get_field :named_name curarg)))
		  (let ( (curbind
			  (instance class_formal_binding 
				    :binder curarg
				    :fbind_type argtype)) )
		    (if (== argmode :checkargs)
			(if (or (not (is_a argtype class_ctype))
				(not (is_string (unsafe_get_field :ctype_parstring argtype))))
			    (error_at argloc "invalid argument type $1 in formal arglist $2"_
				      (get_field :named_name argtype)
				      (get_field :named_name curarg))))
		    (put_int curbind argrk)
		    (mapobject_put argmap curarg curbind)
		    (list_append bndlist curbind)
		    (setq argrk (+i argrk 1))
		    )
		  (void)
		  )
		( (is_a curarg class_formal_binding)
		  (let ( (cursymb (get_field :binder curarg))
			 )
		    (if (mapobject_get argmap cursymb)
			(error_at argloc "duplicate macro-expanded argument $1 in formal arglist"_
				  (get_field :named_name cursymb)))
		    (put_int curarg argrk)
		    (mapobject_put argmap cursymb curarg)
		    (list_append bndlist curarg)
		    (setq argrk (+i argrk 1))
		    )
		  (void)
		  )
		(:else 
		 (debug "unexpected argument in formal arglist" curarg)
		 (let ( (discrarg  (discrim curarg) ))
		   (error_at argloc "unexpected argument of discriminant $1 in formal arglist"_
			     (unsafe_get_field :named_name discrarg))
		   )
		 (void)
		 ))
	       (setq curpair (pair_tail curpair))))
;;; second loop to fill the bindings tuple
    (let ( (bndtup (make_multiple tupdis argrk)) 
	   (:long ix 0)
	   (bndpair (list_first bndlist))
	   )
      (forever bndloop
	       (if (null bndpair) (exit bndloop))
	       (assert_msg "check bndpair" (is_pair bndpair) bndpair)
	       (let ( (curbnd (pair_head bndpair)) )
		 (assert_msg "check curbnd" (is_a curbnd class_any_binding) curbnd)
		 (multiple_put_nth bndtup ix curbnd)
		 )
	       (setq ix (+i ix 1))
	       (setq bndpair (pair_tail bndpair))
	       )
      (debug "lambda_arg_bindings result bndtup" bndtup)
      (return bndtup)
      )))




;;;;;;;;;;;;;;;; install an initial macro expanser
(defun install_initial_macro (symb expander)
  ;;(debug "install_initial_macro symb" symb)
  (assert_msg "check symb" (is_a symb class_symbol) symb)
  (assert_msg "check expander" (is_closure expander) expander)
  (let ( (mbind (instance class_macro_binding 
			  :binder symb
			  :mbind_expanser expander
			  )) )
    (put_env initial_environment mbind)
    ;;(debug "install_initial_macro done symb" symb)
    (return)
    ))

;;;;;;;;;;;;;;;; install an initial patmacro expanser
(defun install_initial_patmacro (symb patexpander macexpander)
  ;(debug "install_initial_patmacro symb" symb)
  (assert_msg "check symb" (is_a symb class_symbol) symb)
  (assert_msg "check patexpander" (is_closure patexpander) patexpander)
  (assert_msg "check macexpander" (is_closure macexpander) macexpander)
  (let ( (mbind (instance class_patmacro_binding 
			  :binder symb
			  :mbind_expanser macexpander
			  :patbind_expanser patexpander
			  )) )
    (put_env initial_environment mbind)
    ;;(debug "install_initial_patmacro done symb" symb "\n.. mbind" mbind)
    (return)
    ))



(defprimitive warn_shadow () :long
  "warn_shadow")
;;;;;;;;;;;;;;;;
;;;;;; warn if a symbol redefines something
(defun warn_if_redefined (symb env loc)
  (assert_msg "check symb" (is_a symb class_symbol) symb)
  (assert_msg "check env" (is_a env class_environment) env)
  (and 
   (warn_shadow)
   (find_env env symb)
   (warning_strv loc "symbol redefinition masks previous" 
		 (unsafe_get_field :named_name symb))
   ))

;;;;;;;;;;;;;;;;
;;;;;; parse a pairlist as a C code expansion, return a tuple

(defun flatten_for_c_code_expansion (loc comp flatlist)
  (assert_msg "check flatlist" (is_list flatlist) flatlist)
  ;;(debug "flatten_for_c_code_expansion comp" comp)
  ;;(debug "flatten_for_c_code_expansion initial flatlist" flatlist)
  (cond    
   ( (null comp)
     ;;(shortbacktrace_dbg "flatten_for_c_code_expansion null comp" 15)
     (error_at loc "null component for C chunk" )
     (return))
   ( (is_a comp class_symbol)
     (list_append flatlist comp)
     )
   ( (is_string comp)
     (list_append flatlist (make_string discr_verbatim_string comp))
     )
   ( (is_list comp)
     (foreach_pair_component_in_list
      (comp)
      (curpair curcomp)
      ;;(debug "flatten_for_c_code_expansion curcomp in list" curcomp)
      (flatten_for_c_code_expansion loc curcomp flatlist)
      ;;(debug "flatten_for_c_code_expansion done curcomp list" curcomp)
      )
     )
   ( (is_a comp class_sexpr)
     (let ( (subloc (get_field :loca_location comp)) 
	    (subcontent (get_field :sexp_contents comp))
	    )
       (foreach_pair_component_in_list 
	(subcontent)
	(cursubpair cursubcomp)
	;;(debug "flatten_for_c_code_expansion cursubcomp in sexp" cursubcomp)
	(flatten_for_c_code_expansion subloc cursubcomp flatlist)
	;;(debug "flatten_for_c_code_expansion done cursubcomp sexp" cursubcomp)
	))
     )
   (:else
    (shortbacktrace_dbg "flatten_for_c_code_expansion strange comp" 15)
    (error_at loc "unexpected component for C chunk of discriminant $1" 
		(get_field :named_name (discrim comp)))
    )
   )
  ;;(debug "flatten_for_c_code_expansion final flatlist" flatlist)
  )

;; parse a pair list into a C code expansion, perhaps flattening it
(defun parse_pairlist_c_code_expansion (loc curpair)
  (debug "parse_pairlist_c_code_expansion loc" loc)
  (debug "parse_pairlist_c_code_expansion curpair" curpair)
  (let ( (flatlist (make_list discr_list)) )
    (forever 
     comploop
     (if (not (is_pair curpair)) (exit comploop))
     (let ( (pairhd (pair_head curpair)) )
       (debug "parse_pairlist_c_code_expansion loop pairhd" pairhd)
       (flatten_for_c_code_expansion loc pairhd flatlist))
     (setq curpair (pair_tail curpair))
     )
    (debug "parse_pairlist_c_code_expansion flatlist" flatlist)
    (let ( (tupexp (list_to_multiple flatlist discr_multiple)) )
      (debug "parse_pairlist_c_code_expansion tupexp" tupexp)
      (assert_msg "check tupexp" (is_multiple tupexp) tupexp)
      (return tupexp)
      )))

;; utility to check that a C expansion has good symbols; every symbol
;; should be in the substitution map
(defun check_c_expansion (etuple loc substmap :cstring msg)
  (debug "check_c_expansion" " etuple=" etuple " loc=" loc " substmap=" substmap " msg=" msg)
  (shortbacktrace_dbg "check_c_expansion" 15)
  (foreach_in_multiple
   (etuple)
   (ecomp :long ix)
   (debug "check_c_expansion" " ecomp=" ecomp " #ix=" ix)
   (cond 
    ( (null ecomp)
      (error_at loc "null component in C expansion")
      (void)
      )
    ( (is_a ecomp class_keyword)
      (debug "check_c_expansion" " keyword ecomp" ecomp)
      (error_at loc "unexpected keyword $1 in C expansion, $2"
		  (unsafe_get_field :named_name ecomp) msg)
      )
    ( (is_a ecomp class_symbol)
      (if (null (mapobject_get substmap ecomp))
	  (progn
	    (debug "check_c_expansion" " ecomp" ecomp)
	    (error_at loc "unexpected symbol $1 in C expansion, $2"
		      (unsafe_get_field :named_name ecomp) msg)
	    ))
      ()
      )
    ( (is_string ecomp)
      ()
      )
    (:else 
     (warning_strv loc "unexpected C expansion component of " 
		   (get_field :named_name (discrim ecomp)))
     ()
     ))))



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;; register the melt_translate_run_macroexpansions_list
(defvar melt_transrunmacro_clos)
(defun melt_register_translator_runner_macroexpansions (clos)
  :doc #{$MELT_REGISTER_TRANSLATOR_RUNNER_MACROEXPANSIONS is an
  internal utility to enable forward reference to
  melt_translate_run_macroexpansions_list defined in
  @file{warmelt-outobj.melt}.}#
  (debug "melt_register_translator_runner_macroexpansions clos=" clos)
  (shortbacktrace_dbg "melt_register_translator_runner_macroexpansions" 15)
  (assert_msg "check clos" (or (is_closure clos) (null clos)) clos)
  (setq melt_transrunmacro_clos clos)
)


;; invoke the melt_translate_run_macroexpansions_list from warmelt-outobj.melt
(defun melt_invoke_translator_runner_macroexpansions (lismexp env modctx)
  (debug "melt_invoke_translator_runner_macroexpansions lismexp=" lismexp "\n.. env=" env 
	 "\n.. modctx=" modctx)
  (shortbacktrace_dbg "melt_invoke_translator_runner_macroexpansions" 32)
  (let ( (clos melt_transrunmacro_clos)
	 )
    (unless (is_closure clos)
      (error_at () "MELT has invalid macro translating running macroexpansions function - corruption")
      (return))
    (when (>i (melt_error_counter) 0)
      (error_at () "MELT won't translate running macroexpansions since got errors")
      (return))
    (debug "melt_invoke_translator_runner_macroexpansions melt_transrunmacro_clos=" clos
	   "\n... env=" debug_less env "\n... modctx=" debug_less modctx)
    (assert_msg "check clos" (is_closure clos) clos)
    (assert_msg "check lismexp" (is_list lismexp) lismexp)
    (let ( (res (clos lismexp env modctx))
	   )
    (when (>i (melt_error_counter) 0)
      (error_at () "MELT got errors after translate running macroexpansions")
      (return))
      (debug "melt_invoke_translator_runner_macroexpansions res=" res)
      (return res))))
  
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;; macro expansers

;;; (defprimitive name bindings :type [:doc documentation] expansion...)
;; the defprimitive expander
(defun mexpand_defprimitive (sexpr env mexpander modctx)
  (debug "mexpand_defprimitive sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (docv ())
	 )
    (if (is_not_a symb class_symbol)
	(error_at loc "missing symbol for (DEFPRIMITIVE symb args type  [:doc documentation] expansion...)"_))
    (setq curpair (pair_tail curpair))
    ;; parse the formal arguments and check that they are not variadic
    (let ( (btup (lambda_arg_bindings (pair_head curpair) () env mexpander modctx))
	   )
      (when (is_a btup discr_variadic_formal_sequence)
	    (error_at 
	     loc
	     "(DEFPRIMITIVE $1 ...) cannot have variadic formals, but ending with :REST"
	     (get_field :named_name symb))
	    (return)
	    )
      (setq curpair (pair_tail curpair))
      ;; parse the type keyword
      (let ( (typkw  (pair_head curpair)) )
	(when (is_not_a typkw class_keyword)
	    (error_at loc "missing type keyword for (DEFPRIMITIVE $1 <args> <type> [:doc documentation] expansion...)"_ (get_field :named_name symb))
	    (return))
	(let ( (cty (unsafe_get_field :symb_data typkw)) 
	       (typknam (unsafe_get_field :named_name typkw))
	       )
	  (when (is_not_a cty class_ctype)
		(debug "mexpand_defprimitive bad cty" typkw)
		(error_at loc "bad type keyword $1 for "_  typknam)
		(return ())
		)
	  (cond ( (== (unsafe_get_field :ctype_keyword cty) typkw)
		  ()
		  )
		( (== (unsafe_get_field :ctype_altkeyword cty) typkw)
		  (warning_strv loc "using obsolete ctype keyword" typknam)
		  (inform_strv loc "prefered ctype is" (get_field :named_name (get_field :ctype_keyword cty)))
		  )
		(:else
		 (debug "mexpand_defprimitive strange typkw" typkw)
		 (error_at loc "invalid type keyword $1 for DEFPRIMITIVE"_
			     typknam)
		 (return ())   
		 ))
	  ;; parse the rest as to be expanded
	  (setq curpair (pair_tail curpair))
	  (when (== (pair_head curpair) ':doc)
	    (setq curpair (pair_tail curpair))
	    (if docv (error_at loc "duplicate :doc in DEFPRIMITIVE"))
	    (setq docv (pair_head curpair))
	    (setq curpair (pair_tail curpair))
	    )
	  (let (
		(curhead (pair_head curpair))
		(exploc (or (get_field :loca_location curhead) loc))
		(etuple (parse_pairlist_c_code_expansion loc curpair))
		(substmap (make_mapobject discr_map_objects
					  (+i 5 (*i 2 (multiple_length btup)))))
		(sdefpri
		 (instance class_source_defprimitive
			   :loca_location loc
			   :sdef_name symb
			   :sdef_doc docv
			   :sformal_args btup
			   :sprim_type cty
			   :sprim_expansion etuple
			   :sprim_exploc exploc))
		(primit
		 (instance class_primitive
			   :named_name (unsafe_get_field :named_name symb)
			   :prim_formals btup
			   :prim_type cty
			   :prim_expansion etuple))
		(pbind
		 (instance class_primitive_binding
			   :binder symb
			   :pbind_primdef sdefpri
			   :pbind_primitive primit
			   ))
		)
	    ;; fill the substmap according to btup to check the C expansion
	    (foreach_in_multiple
	     (btup)
	     (curbind :long bix)
	     (assert_msg "check curbind" (is_a curbind class_formal_binding) curbind)
	     (mapobject_put substmap (get_field :binder curbind) curbind)
	     )
	    (debug "defprimitive primit" primit)
	    (check_c_expansion etuple loc substmap)
	    ;;
	    (warn_if_redefined symb env loc)
	    (put_env env pbind)
	    (debug "mexpand_defprimitive registering device sdefpri=" sdefpri " primit=" primit)
	    (register_generator_device sdefpri primit modctx)
	    (debug "mexpand_defprimitive result sdefpri" sdefpri)
	    (return sdefpri)
	    ))))))
(install_initial_macro 'defprimitive mexpand_defprimitive)
(export_macro defprimitive mexpand_defprimitive
	      :doc #{The $DEFPRIMITIVE macro defines new primitive
operations by their C expansion. Syntax is ($DEFPRIMITIVE @var{name}
@var{formals} @var{type} [:doc @var{documentation}] @var{expansion})
which defines a primitive of given @var{name} with formal arguments
@var{formals}, result c-type @var{type}, optional @var{documentation},
and given @var{expansion}. A macro is expanded into a C instruction if
its c-type is @code{:void}, otherwise into a C expression.  Primitives
have to be exported with $EXPORT_VALUES to be visible in other
modules.  See also the classes $CLASS_PRIMITIVE, and
$CLASS_PRIMITIVE_BINDING and the $CODE_CHUNK macro.}# )



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; the defciterator expander
;;(DEFCITERATOR symb startformals statesymb varformals [:doc documentation] expbefore expafter)
(defun mexpand_defciterator (sexpr env mexpander modctx)
  (debug "mexpand_defciterator sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (symbname (get_field :named_name symb))
	 ;; the following variables are set later by setq
	 (bstartup ())			;the start formals tuple
	 (statsymb ())			;the state symbol
	 (blocvtup ())			;the local var formals tuple
	 (docv ())
	 (expbef ())		     ;the tuple expansion before tuple
	 (expaft ())		     ;the tuple expansion after tuple
	 (befloc ())		     ;location of before chunk
	 (aftloc ())		     ;location of after chunk
	 )
    (when (is_not_a symb class_symbol)
      (error_at loc 
		   "missing symbol for (DEFCITERATOR symb startformals statesymb locformals expbefore expafter)"_)
      (return)
      )
    (setq curpair (pair_tail curpair))
    ;; parse the formal start arguments
    (setq bstartup (lambda_arg_bindings (pair_head curpair) () env mexpander modctx))
    (setq curpair (pair_tail curpair))
    (setq statsymb (pair_head curpair))
    (when (is_not_a statsymb class_symbol)
      (error_at loc 
		"missing statsymb for (DEFCITERATOR $1 startformals statesymb locformals expbefore expafter)"_ symbname)
      (return))
    (when (is_a bstartup discr_variadic_formal_sequence)
	  (error_at loc
		    "(DEFCITERATOR $1 startformals...) cannot have variadic start formals"_ symbname)
	  (return))
    ;; parse the formal local arguments
    (setq curpair (pair_tail curpair))
    (setq blocvtup  (lambda_arg_bindings (pair_head curpair) () env mexpander modctx))
    (when (is_a blocvtup  discr_variadic_formal_sequence)
      (error_at loc
		"(DEFCITERATOR $1 startformals state localformals...) cannot have variadic local formals" symbname)
      (return))
    (setq curpair (pair_tail curpair))
    ;; parse the documentation, if any
    (when (== (pair_head curpair) ':doc)
      (setq curpair (pair_tail curpair))
      (if docv (error_at loc
			 "duplicate documentation in DEFCITERATOR $1" symbname))
      (setq docv (pair_head curpair))
      (setq curpair (pair_tail curpair)))
    ;; parse the before expansion
    (let ( (sexpbef (pair_head curpair)) )
      (when (is_not_a sexpbef class_sexpr)
	    (error_at loc
		      "missing before expansion for  (DEFCITERATOR $1 startformals statesymb locformals expbefore expafter)"_ 
		      symbname)
	    (return))
      (setq befloc (get_field :loca_location sexpbef))
      (setq expbef (parse_pairlist_c_code_expansion loc (list_first (unsafe_get_field :sexp_contents sexpbef))))
      )
    (setq curpair (pair_tail curpair))
    ;; parse the after expansion
    (let ( (sexpaft (pair_head curpair)) )
      (when (is_not_a sexpaft class_sexpr)
	    (error_at loc 
		      "missing after expansion for  (DEFCITERATOR $1 startformals statesymb locformals expbefore expafter)"_ 
		      symbname)
	    (return))
      (setq aftloc (get_field :loca_location sexpaft))
      (setq expaft  (parse_pairlist_c_code_expansion loc (list_first (unsafe_get_field :sexp_contents sexpaft))))
      )
    ;; parse the documentation, if any
    (if (== (pair_head curpair) ':doc)
	(progn
	  (setq curpair (pair_tail curpair))
	  (if docv (error_at loc
			     "duplicate documentation in DEFCITERATOR $1"_ symbname))
	  (setq docv (pair_head curpair))
	  (setq curpair (pair_tail curpair))))
    ;; make the citerator and binding
    (let ( (citer (instance class_citerator
			    :named_name (unsafe_get_field :named_name symb)
			    :citer_start_formals bstartup
			    :citer_state statsymb
			    :citer_body_formals blocvtup
			    :citer_expbefore expbef
			    :citer_expafter expaft
			    ))
	   (citbind (instance class_citerator_binding
			      :binder symb
			      ;; :cbind_citerdef bound later
			      :cbind_citerator citer
			      ))
	   (srcit (instance class_source_defciterator
			    :loca_location loc
			    :sdef_name symb
			    :sdef_doc docv
			    :sformal_args bstartup
			    :sciterdef_citerator citer
			    :sciterdef_beforeloc befloc
			    :sciterdef_afterloc aftloc
			    ))
	   (substmap (make_mapobject 
		      discr_map_objects
		      (+i 7 (+i (*i 2 (multiple_length bstartup))
				(*i 2 (multiple_length blocvtup))))))
	   ) ;; fill the substmap
      (debug "srcit citer" srcit)
      (mapobject_put substmap statsymb statsymb)
      (debug "bstartup citer" bstartup)
      (foreach_in_multiple
       (bstartup)
       (cursbind :long bsix)
       (assert_msg "check start cursbind" (is_a cursbind class_formal_binding) cursbind)
       (mapobject_put substmap (get_field :binder cursbind) cursbind))
      (debug "blocvtup citer" blocvtup)
      (foreach_in_multiple
       (blocvtup)
       (curlbind :long blix)
       (debug "curlbind local citer" curlbind)
       (assert_msg "check local curlbind" (is_a curlbind class_any_binding) curlbind)
       (mapobject_put substmap (get_field :binder curlbind) curlbind))
;;; check the expansions
      (check_c_expansion expbef loc substmap "DEFCITERATOR before")
      (check_c_expansion expaft loc substmap "DEFCITERATOR after")
      ;; fill the citerator binding
      (unsafe_put_fields citbind :cbind_citerdef srcit)
      (put_env env citbind)
      (debug "mexpand_defciterator registering device srcit=" srcit " citer=" citer)
      (register_generator_device srcit citer modctx)
      (debug "mexpand_defciterator parsed citerator citer" citer)
      (return srcit)
      )))
(install_initial_macro 'defciterator mexpand_defciterator)
(export_macro defciterator mexpand_defciterator
	      :doc #{The $DEFCITERATOR macro defines a c-iterator
which itself implements iterative @code{for}-like loops. Syntax
is ($DEFCITERATOR @var{name} @var{start-formals} @var{state-symbol}
@var{variable-formals} [:doc @var{documentation}]
@var{before-expansion} @var{after-expansion}). To be visible outside
the module, the c-iterator should be exported using
$EXPORT_VALUES. See also $CLASS_CITERATOR. }#)



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; the defcmatcher expander
;;(DEFCMATCHER  symb match&in-formals out-formals state-sym [:doc documentation]
;;              test-expansion fill-expansion oper-expansion)
(defun mexpand_defcmatcher (sexpr env mexpander modctx)
  (debug "mexpand_defcmatcher sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (symbname (get_field :named_name symb))
	 ;; the following variables are set later by setq
	 (sformals ())			;match & input fmals
	 (matchformal ())		;the match formal binding
	 (informals ())			;input formals tuple
	 (outformals ())		;output formals tuple
	 (statesym ())			;state symbol
	 (exptest ())			;test expansion tuple
	 (expfill ())			;fill expansion tuple
	 (expoper ())			;operand expansion tuple
	 (docv ())			;documentation
	 (loctest ())			;location of test
	 (locfill ()) 			;location of fill
	 (locoper ())			;location of oper
	 )
    ;; check the symb
    (debug "mexpand_defcmatcher symb" symb)
    (when (is_not_a symb class_symbol)
      (error_at
       loc 
       "symbol expected for (DEFCMATCHER <symb> <ins> <outs> <statesym> <test> <fill> <oper>)"_)
      (return))
    (setq curpair (pair_tail curpair))
    ;; parse the match & in formals 
    (let ( (matinformals (lambda_arg_bindings (pair_head curpair) () env mexpander modctx))
	   (:long nbmatinformals (multiple_length matinformals)) 
	   )
      (when (<i nbmatinformals 1)
	(error_at loc 
		  "empty ins for (DEFCMATCHER $1 <ins> <outs> <statesym> <test> <fill> <oper>)"_ symbname)
	(return))
      (when (is_a matinformals discr_variadic_formal_sequence)
	(error_at loc 
		  "(DEFCMATCHER $1 <ins> ...) cannot have variadic input formals"_ symbname)
	(return)
	)
      (setq sformals matinformals)
      (setq matchformal (multiple_nth matinformals 0))
      (debug "mexpand_defcmatcher matchformal" matchformal)
      (assert_msg "check matchformal" (is_a matchformal class_formal_binding) matchformal)
      (setq informals (make_multiple discr_multiple (-i nbmatinformals 1)))
      (foreach_in_multiple 
       (matinformals)
       (comp :long ix) (if (>i ix 0) (multiple_put_nth informals (-i ix 1) comp)))
      (debug "mexpand_defcmatcher informals" informals)
      )
    ;; parse the out formals
    (setq curpair (pair_tail curpair))
    (setq outformals (lambda_arg_bindings (pair_head curpair) () env mexpander modctx))
    (debug "mexpand_defcmatcher outformals" outformals)
    (when (not (is_multiple outformals))
      (error_at loc "bad outs for (DEFCMATCHER $1 <ins> <outs> <statesym> <test> <fill> <oper>)"_ symbname)
      (return))
    (when (is_a outformals discr_variadic_formal_sequence)
      (error_at loc "out formals for  (DEFCMATCHER $1 <ins> <outs> ...) cannot be variadic" symbname)
      (return))
    ;; parse the state symbol
    (setq curpair (pair_tail curpair))
    (setq statesym (pair_head curpair))
    (when (is_not_a statesym class_symbol)
      (debug "mexpand_defcmatcher bad statesym" statesym)
      (error_at loc "bad statesym for (DEFCMATCHER $1 <ins> <outs> <statesym> <test> <fill> <oper>)"_ symbname)
      (return))
    (debug "mexpand_defcmatcher statesym" statesym)
    (setq curpair (pair_tail curpair))
    ;; parse the documentation if any
    (when (== (pair_head curpair) ':doc)
      (setq curpair (pair_tail curpair))
      (if docv (error_at  loc "duplicate documentation in DEFCMATCHER $1" symbname))
      (setq docv (pair_head curpair))
      (setq curpair (pair_tail curpair))
      )
    ;; parse the test expansion
    (let ( (sexptest (pair_head curpair)) )
      (when (and sexptest (is_not_a sexptest class_sexpr))
	(debug "mexpand_defcmatcher bad sexptest" sexptest)
	(error_at loc "bad test expansion in (DEFCMATCHER $1 <ins> <outs> <statesym> <test> <fill> <oper>)"_ symbname)
	(return))
      (setq loctest (or (get_field :loca_location sexptest) loc))
      (if sexptest
	  (setq exptest 
		(parse_pairlist_c_code_expansion 
		 loc
		 (list_first (unsafe_get_field :sexp_contents sexptest)))))
      )
    (debug "mexpand_defcmatcher exptest" exptest)
    ;; parse the fill expansion
    (setq curpair (pair_tail curpair))
    (let ( (sexpfill (pair_head curpair)) )
      (when (and sexpfill (is_not_a sexpfill class_sexpr))
	(error_at loc "bad fill expansion in (DEFCMATCHER $1 <ins> <outs> <statesym> <test> <fill> <oper>)"_ symbname)
	(return))
      (setq locfill (or (get_field :loca_location sexpfill) loc))
      (if sexpfill
	  (setq expfill
		(parse_pairlist_c_code_expansion 
		 loc (list_first (unsafe_get_field :sexp_contents sexpfill)))))
      )
    (debug "mexpand_defcmatcher expfill" expfill)
    ;; parse the operate expansion
    (setq curpair (pair_tail curpair))
    (let ( (sexpoper (pair_head curpair)) )
      (when (and sexpoper (is_not_a sexpoper class_sexpr))
	(error_at loc "bad oper expansion in (DEFCMATCHER $1 <ins> <outs> <statesym> <test> <fill> <oper>)"_ symbname)
	(return))
      (setq locoper (or (get_field :loca_location sexpoper) loc))
      (setq expoper
	    (if sexpoper
		(parse_pairlist_c_code_expansion loc (list_first (unsafe_get_field :sexp_contents sexpoper)))))
      )
    (debug "mexpand_defcmatcher expfill" expoper)
    ;; check nothing more
    (setq curpair (pair_tail curpair))
    (if curpair
	(warning_plain loc "extra in (DEFCMATCHER <symb> <ins> <outs> <statesym> <test> <fill> <oper>)"_))
    (assert_msg "check matchformal again" (is_a matchformal class_formal_binding) matchformal)
    ;; build the defcmatcher
    (let (
	  (cmatch (instance class_cmatcher
			    :named_name (unsafe_get_field :named_name symb)
			    :amatch_in informals
			    :amatch_matchbind matchformal
			    :amatch_out outformals
			    :cmatch_state statesym
			    :cmatch_exptest exptest
			    :cmatch_expfill expfill
			    :cmatch_expoper expoper
			    ))
	  (sdefcmatch (instance  class_source_defcmatcher
				 :loca_location loc
				 :sdef_name symb
				 :sdef_doc docv
				 :sformal_args sformals
				 :scmatdef_cmatcher cmatch
				 :scmatdef_testloc loctest
				 :scmatdef_fillloc locfill
				 :scmatdef_operloc locoper)) 
	  (cmbind (instance class_cmatcher_binding
			    :binder symb
			    :cmbind_matcher cmatch))
	  (substmap 
	   (make_mapobject 
	    discr_map_objects
	    (+i 7 (*i 2 (+i (multiple_length informals)
			    (multiple_length outformals))))))
	  )
      ;; fill the substmap
      (mapobject_put substmap statesym statesym)
      (mapobject_put substmap (get_field :binder matchformal) matchformal)
      (foreach_in_multiple
       (informals)
       (curibind :long ibix)
       (assert_msg "check input curibind" (is_a curibind class_formal_binding) curibind)
       (mapobject_put substmap (get_field :binder curibind) curibind))
      (foreach_in_multiple
       (outformals)
       (curobind :long obix)
       (assert_msg "check output curbind" (is_a curobind class_formal_binding) curobind)
       (mapobject_put substmap (get_field :binder curobind) curobind))
      ;; check the expansions
      (check_c_expansion exptest loc substmap "DEFCMATCHER test")
      (check_c_expansion expfill loc substmap "DEFCMATCHER fill")
      (check_c_expansion expoper loc substmap "DEFCMATCHER operation")
      (debug "mexpand_defcmatcher sdefcmatch" sdefcmatch)
      (put_env env cmbind)
      (debug "mexpand_defcmatcher registering device sdefcmatch=" sdefcmatch " cmatch=" cmatch)
      (register_generator_device sdefcmatch cmatch modctx)
      (return sdefcmatch)
      )
    )
  )
(install_initial_macro 'defcmatcher mexpand_defcmatcher)
(export_macro defcmatcher mexpand_defcmatcher
 :doc #{The $DEFCMATCHER macro defines pattern-matching operator by
 their C expansion. Syntax is (DEFCMATCHER symbol match&ins-formals
 out-formals state-symbol [:doc documentation] test-expansion
 fill-expansion [operator-expansion]).}# )



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; probably (DEFUNMATCHER <symb> <informals> <outformals> [:doc documentation] <matchfun> [<applyfun> [<data>]])
(defun mexpand_defunmatcher (sexpr env mexpander modctx)
  (debug "mexpand_defunmatcher sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (symbname (get_field :named_name symb))
	 ;; the following variables are set later by setq
	 (sformals ())			;match & input fmals
	 (matchformal ())		;the match formal binding
	 (informals ())			;input formals tuple
	 (outformals ())		;output formals tuple
	 (matchfunx ())			;the matcher function expr
	 (applyfunx ())			;the apply function expr
	 (datax ())			;extra data expr
	 (docv ())
	 )
    ;; check symb
    (debug "mexpand_defunmatcher symb" symb)
    (when (is_not_a symb class_symbol)
      (error_at
       loc 
       "symbol expected for (DEFUNMATCHER <symb> <ins> <outs> [:doc docum] <matchfun> <applyfun> [<data>])"_)
      (return))
    (setq curpair (pair_tail curpair))
    ;; parse the match & in formals 
    (let ( (matinformals (lambda_arg_bindings (pair_head curpair) () env mexpander modctx))
	   (:long nbmatinformals (multiple_length matinformals)) 
	   )
      (when (<i nbmatinformals 1)
	(error_at loc "empty ins for (DEFUNMATCHER $1 <ins> <outs> [:doc docum] <matchfun> <applyfun> [<data>])"_ symbname)
	(return))
      (when (is_a matinformals discr_variadic_formal_sequence)
	(error_at loc "(DEFUNMATCHER $1  <ins> ...) inputs cannot be variadic with last :rest formal"
		  symbname)
	(return)
	)
      (setq sformals matinformals)
      (setq matchformal (multiple_nth matinformals 0))
      (debug "mexpand_defunmatcher matchformal" matchformal)
      (setq informals (make_multiple discr_multiple (-i nbmatinformals 1)))
      (foreach_in_multiple 
       (matinformals)
       (comp :long ix) (if (>i ix 0) (multiple_put_nth informals (-i ix 1) comp)))
      (debug "mexpand_defunmatcher informals" informals)
      )
    ;; parse the out formals
    (setq curpair (pair_tail curpair))
    (setq outformals (lambda_arg_bindings (pair_head curpair) () env mexpander modctx))
    (when (not (is_multiple outformals))
      (error_at loc "bad outs for (DEFUNMATCHER $1 <ins> <outs>[:doc docum]  <matchfun> <applyfun> [<data>])"_ symbname)
      (return))
    (when (is_a outformals discr_variadic_formal_sequence)
      (error_at loc "(DEFUNMATCHER $1  <ins> <outs> ...) outputs cannot be variadic with last :rest formal"
		symbname)
      (return)
      )
    (setq curpair (pair_tail curpair))
    ;; parse the documentation if any
    (if (== (pair_head curpair) ':doc)
	(progn
	  (setq curpair (pair_tail curpair))
	  (if docv (error_plain loc "duplicate documentation for DEFUNMATCHER"))
	  (setq docv (pair_head curpair))
	  (setq curpair (pair_tail curpair))
	  ))
    ;; parse & macroexpand the matchfun expr
    (let ( (mfa (pair_head curpair)) )
      (if mfa
	  (setq matchfunx (mexpander mfa env mexpander modctx))
	(error_at loc "bad matchfun for (DEFUNMATCHER $1 <ins> <outs> <matchfun> <applyfun> [<data>])"_ symbname))
      )
    (debug "mexpand_defunmatcher matchfunx" matchfunx)
    ;; parse & macroexpand the applyfun expr if given
    (setq curpair (pair_tail curpair))
    (let ( (afa (pair_head curpair)) )
      (if afa
	  (setq applyfunx (mexpander afa env mexpander modctx))
	;; apply function is optional, can be missing.
	)
      )
    (debug "mexpand_defunmatcher applyfunx" applyfunx)
    ;; parse & macroexpand the data expr
    (setq curpair (pair_tail curpair))
    (let ( (dta (pair_head curpair)) )
      (if dta
	  (setq datax (mexpander dta env mexpander modctx))
	;; data is optional, so no error if missing
	))
    (debug "mexpand_defunmatcher datax" datax)
    ;; check for no extra stuff
    (setq curpair (pair_tail curpair))
    (if curpair 
	(error_at loc "extra for (DEFUNMATCHER $1 <ins> <outs> <matchfun> [<applyfun> [<data>]])"_ symbname))
    (let (
	  ;; make a class_source_defunmatcher with :loca_location :sdef_name
	  ;; :sformal_args :sfumatdef_matchf :sfumatdef_applyf
	  ;; :sfumatdef_data
	  (sdfum (instance class_source_defunmatcher
			   :loca_location loc
			   :sdef_name symb
			   :sdef_doc docv
			   :sformal_args sformals
			   :sfumatdef_ins informals
			   :sfumatdef_outs outformals
			   :sfumatdef_matchf matchfunx
			   :sfumatdef_applyf applyfunx
			   :sfumatdef_data datax))
	  ;; make an (uncompletely filled) funmatcher
	  (fuma (instance class_funmatcher
			  :named_name (unsafe_get_field :named_name symb)
			  :amatch_in informals
			  :amatch_matchbind matchformal
			  :amatch_out outformals
			  :fmatch_matchf ()
			  :fmatch_applyf ()
			  :fmatch_data ()
			  ))
	  ;; make the binding
	  (fmbind (instance class_funmatcher_binding
			    :binder symb
			    :fmbind_funmatcher fuma
			    :fmbind_defunmatcher sdfum
			    ))
	  )
      (put_env env fmbind)
      (debug "mexpand_defunmatcher made fuma" fuma)
      (debug "mexpand_defunmatcher fmbind" fmbind)
      (debug "mexpand_defunmatcher return sdfum" sdfum)
      (return sdfum)
      )))
    
(install_initial_macro 'defunmatcher mexpand_defunmatcher)
(export_macro defunmatcher mexpand_defunmatcher
:doc #{The $DEFUNMATCHER syntax defines a matcher thru a MELT
function. Syntax is (DEFUNMATCHER <symbol> <in-formals> <out-formals>
[:doc docum] <match-function> [<apply-function> [<data>]])}#)


;;;;;;;;;;;;;;;;;; the defun expander
;;;(DEFUN funame formals [:doc documentation] body...)
(defun mexpand_defun (sexpr env mexpander modctx)
  (debug "mexp.defun sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (symbname (get_field :named_name symb))
	 (newenv (fresh_env env))
	 (docv ())
	 (fbind 
	  (instance class_function_binding
		    :binder symb
		    :fubind_defun ()	;to be filled later
		    ))
	 )
    (if (is_not_a symb class_symbol)
	(error_plain loc "missing symbol for DEFUN"_))
    (warn_if_redefined symb env loc)
    (put_env env fbind)
    (setq curpair (pair_tail curpair))
    ;; parse the formal arguments
    (let ( (curpairhead (pair_head curpair)) 
	   (btup 
	    (cond ( (null curpairhead) 
		    (make_multiple discr_multiple 0) )
		  ( (is_a curpairhead class_sexpr)
		    (lambda_arg_bindings (pair_head curpair) :checkarg env mexpander modctx))
		  (:else
		   (debug "mexpand_defun strange arglist curpairhead" curpairhead)
		   (error_at loc "missing or invalid arglist for DEFUN $1"_ symbname)
		   ()
		   )))
	   )
      (when (not (is_multiple btup))
	    (debug "mexpand_defun strange btup" btup)
	    (error_at loc "missing formal arguments for DEFUN $1"_ symbname))
      (foreach_in_multiple (btup) (fb :long bix) (put_env newenv fb))
      (setq curpair (pair_tail curpair))
      ;; handle the optional :doc documentationvalue
      (when (== (pair_head curpair) ':doc)
	    (setq curpair (pair_tail curpair)) ;; consume :doc
	    ;; the documentation is NOT macro-expanded
	    (setq docv (pair_head curpair))    ;; get the docv
	    (setq curpair (pair_tail curpair))  ;; consume it
	    )
      ;; handle the body
      (let ( (bodytup (expand_pairlist_as_tuple curpair newenv mexpander modctx)) 
	     (sdefun
	      (instance class_source_defun
			:loca_location loc
			:sdef_name symb
			:sdef_doc docv
			:sformal_args btup
			:sfun_body bodytup
			))
	     )
	(put_fields fbind :fubind_defun sdefun)
	(unless (multiple_length bodytup)
	  (error_at loc "missing or empty body for DEFUN $1" symbname))
	(return sdefun)
	))))
(install_initial_macro 'defun mexpand_defun)
(export_macro defun mexpand_defun
	      :doc #{The $DEFUN macro defines a function. Syntax
is ($DEFUN @var{funame} @var{formals} [:doc @var{documentation}]
@var{body}...). The first formal argument, if any, is required to be
of ctype @code{:value}. The expressions in the @var{body} are evaluated
in sequence. The value of the last is returned. See also $RETURN and
$LAMBDA macros. A function defined by $DEFUN has to be exported with 
$EXPORT_VALUES to be visible outside its module.}#)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;; this magic function should expand and compile all the macro definitions of maclist

(defun melt_delayed_macro_expander (mbind maclist env mexpander modctx)
  (debug "melt_delayed_macro_expander mbind=" mbind "\n.. maclist=" maclist
	 "\n.. env=" env
	 "\n.. mexpander=" mexpander
	 "\n.. old-mocx_macrolist=" (get_field :mocx_macrolist modctx) 
	 "\n.. modctx=" debug_less modctx)
  (shortbacktrace_dbg "melt_delayed_macro_expander" 12)
  (assert_msg "check maclist" (is_list maclist) maclist)
  (block_signals 
   () ()
   (put_fields modctx :mocx_macrolist (make_list discr_list)))
  ;;
  (let ( (macroenv (get_field :mocx_macroenv modctx))
	 )
  (debug "melt_delayed_macro_expander maclist=" maclist "\n.. env=" debug_more env
	 "\n.. macroenv=" debug_more macroenv 
	 "\n.. modctx=" debug_less modctx
	 "\n.. mbind=" debug_less mbind "\n")
  (assert_msg "check macroenv" (is_a macroenv class_environment) macroenv)
  (let ( (res (melt_invoke_translator_runner_macroexpansions maclist macroenv modctx))
	 )
    (debug "melt_delayed_macro_expander final res=" res
	   "\n mbind=" mbind)
    )))

;;;;;;;;;;;;;;;;;; the defmacro expander
;;;(DEFMACRO macroname formals [:doc documentation] body...)
(defun mexpand_defmacro (sexpr env mexpander modctx)
  (debug "mexpand_defmacro sexpr=" sexpr "\n.. modctx=" modctx
	 "\n.. env=" env "\n")
  (shortbacktrace_dbg "mexpand_defmacro" 15)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (symbname (get_field :named_name symb))
	 (modinienv (get_field :mocx_initialenv modctx))
	 (modmacroenv (get_field :mocx_macroenv modctx))
	 (maclist (get_field :mocx_macrolist modctx))
	 (newenv (fresh_env modmacroenv))
	 (docv ())
	 (mbind 
	  (instance class_defined_macro_binding
		    :binder symb
		    :mbind_expanser ()	;to be filled later
		    ))
	 (fbind 
	  (instance class_function_binding
		    :binder symb
		    :fubind_defun ()	;to be filled later
		    ))
	 )
    (debug "mexpand_defmacro loc=" debug_less loc "; modmacroenv=" modmacroenv "\n.. newenv=" newenv
	   "\n.. mbind=" mbind)
    (when (is_not_a symb class_symbol)
      (debug "mexpand_defmacro bad symb=" symb " in sexpr=" sexpr)
      (error_at loc "missing symbol for DEFMACRO"_)
      (return))
    (when (null modinienv)
      (error_at loc "DEFMACRO $1 prohibited in cold bootstrap of warmelt-first file"
		symbname)
      (assert_msg "unexpected DEFMACRO in code bootstrap of warmelt-first file" ())
      (return))
    (when (not (is_list maclist))
      (error_at loc "DEFMACRO $1 requires a module context with macro list" symbname)
      (assert_msg "bad maclist in DEFMACRO" () maclist)
      (return))
    (warn_if_redefined symb env loc)
    (put_env env mbind)
    (warn_if_redefined symb newenv loc)
    (put_env modmacroenv fbind)
    (debug "mexpand_defmacro loc=" debug_less loc "; updated env=" debug_more env)
    (debug "mexpand_defmacro loc=" debug_less loc "; updated modmacroenv=" debug_more modmacroenv)
    (setq curpair (pair_tail curpair))
    ;; parse the formal arguments
    (let ( (curpairhead (pair_head curpair)) 
	   (btup 
	    (cond ( (null curpairhead) 
		    (make_multiple discr_multiple 0) )
		  ( (is_a curpairhead class_sexpr)
		    (lambda_arg_bindings (pair_head curpair) :checkarg env mexpander modctx))
		  (:else
		   (debug "mexpand_defmacro strange arglist curpairhead" curpairhead)
		   (error_at loc "missing or invalid arglist for DEFMACRO $1"_ symbname)
		   ()
		   )))
	   )
      (debug "mexpand_defmacro loc=" loc "; btup=" btup)
      (when (not (is_multiple btup))
	(error_at loc "missing formal arguments for DEFMACRO $1"_ symbname)
	(return))
      (foreach_in_multiple 
       (btup) 
       (fb :long bix) 
       (put_env newenv fb))
      (debug "mexpand_defmacro loc=" loc "; updated newenv=" debug_more newenv)
      (setq curpair (pair_tail curpair))
      ;; handle the optional :doc documentationvalue
      (when (== (pair_head curpair) ':doc)
	(setq curpair (pair_tail curpair)) ;; consume :doc
	;; the documentation is NOT macro-expanded
	(setq docv (pair_head curpair))	   ;; get the docv
	(setq curpair (pair_tail curpair)) ;; consume it
	)
      (debug "mexpand_defmacro initial mbind=" mbind "\n.. modctx=" modctx "\n")
      ;; should put a :mbind_expanser closure into mbind
      ;; handle the body
      (let ( (bodytup (expand_pairlist_as_tuple curpair newenv mexpander modctx))
	     (sdefmacro
	      (instance class_source_defmacro
			:loca_location loc
			:sdef_name symb
			:sdef_doc docv
			:sformal_args btup
			:sfun_body bodytup
			:smacro_binding mbind
			))
	     (sinstmacro
	      (instance class_source_macro_installation
			:loca_location loc
			:smacinst_defmacro sdefmacro
			:smacinst_env modmacroenv
			))
	     )
	(debug "mexpand_defmacro loc=" loc "; bodytup=" bodytup "\n.. newenv=" newenv)
	(debug "mexpand_defmacro loc=" loc "; sdefmacro=" sdefmacro "\n.. sinstmacro=" sinstmacro)
	(when (not (is_list maclist))
	  (error_at loc "macros, i.e. DEFMACRO, are forbidden in this module $1" 
		    (get_field :mocx_modulename modctx))
	  (return))
	(put_fields mbind :mbind_defmacro sdefmacro)
	(debug "mexpand_defmacro loc=" loc "; sdefmacro=" sdefmacro "\n old maclist=" maclist 
	       "\n.. modulname=" (get_field :mocx_modulename modctx))
	(debug "mexpand_defmacro loc=" loc "; sinstmacro=" sinstmacro)
	(assert_msg "check maclist" (is_list maclist) maclist)
	(list_append maclist sinstmacro)
	(debug "mexpand_defmacro loc=" loc "; updated maclist=" maclist)
	(put_fields fbind :fubind_defun sdefmacro)
	(debug "mexpand_defmacro loc=" loc "; updated fbind=" fbind
	       "\n.. mbind=" mbind)
	;; we should put a :mbind_expanser closure into mbind
	(put_fields mbind 
		    :mbind_expanser 
		    (lambda (sexprm envm mexpanderm modctxm)
		      (debug "mexpand_defmacro/lambdambind loc=" loc "; sexprm=" sexprm
			     "\n.. envm=" envm
			     "\n.. modctxm=" modctxm "\n")
		      (shortbacktrace_dbg "mexpand_defmacro/lambdambind" 15)
		      (assert_msg "check modctxm" (== modctxm modctx) modctxm modctx)
		      (debug "mexpand_defmacro/lambdambind loc=" loc "; env=" debug_less env 
			     "\n.. envm=" debug_less envm
			     "\n.. newenv=" debug_less newenv
			     "\n.. modinienv=" debug_less modinienv)
		      (let ( (oldmclos (get_field :mbind_expanser mbind))
			     (locm (get_field :loca_location sexprm))
			     )
			(debug "mexpand_defmacro/lambdambind before melt_delayed_macro_expander mbind=" mbind)
			(melt_delayed_macro_expander mbind maclist envm mexpanderm modctx)
			(debug "mexpand_defmacro/lambdambind after melt_delayed_macro_expander mbind=" mbind)
			(assert_msg "check mbind" (is_a mbind class_defined_macro_binding) mbind)
			(let ( (mclos (get_field :mbind_expanser mbind))
			       )
			  (debug "mexpand_defmacro/lambdambind mclos=" mclos "\n.. sexprm=" sexprm)
			  (assert_msg "check mclos" (is_closure mclos) mclos)
			  (when (== oldmclos mclos)
			    (error_at locm "failed to macro-expand macro $1" symbname)
			    (warning_at loc "failed to expand macro $1 defined here" symbname)
			    (return)
			    )
			  (multicall 
			   (expmac othermac)
			   (mclos sexprm envm mexpanderm modctxm)
			   (debug "mexpand_defmacro/lambdambind expmac=" expmac " othermac=" othermac)
			   (return expmac othermac)
			   )
			  ))))
	(debug "mexpand_defmacro loc=" loc "; final mbind=" mbind "\n.. final fbind=" fbind
	       "\n.. sdefmacro=" sdefmacro)
	(return sdefmacro)
	))))

(install_initial_macro 'defmacro mexpand_defmacro)
(export_macro defmacro mexpand_defmacro
	      :doc #{The $DEFMACRO macro defines a macro. Syntax
is ($DEFMACRO @var{funame} @var{formals} [:doc @var{documentation}]
@var{body}...). At most four @var{formals} are permitted of ctype
@code{:value}, for the @var{s-expression} invoking the macro, the
@var{environment} at macro-expansion time, the current
@var{macro-expander} closure and at last the @var{module context}.}#)


;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;; the hook to install a macro
(defhook hook_macro_installer (mbind mexpclos)
  ()
  :void
  :predef HOOK_MACRO_INSTALLER
  :doc #{The internal $HOOK_MACRO_INSTALLER is installing macro, during a translation}#
  (debug "hook_macro_installer" " mbind=" mbind " mexpclos=" mexpclos)
  (shortbacktrace_dbg "hook_macro_installer" 16)
  (assert_msg "check mbind" (is_a mbind class_defined_macro_binding) mbind)
  (assert_msg "check mexpclos" (is_closure mexpclos) mexpclos mbind)
  (put_fields mbind :mbind_expanser mexpclos)
  (debug "hook_macro_installer updated mbind=" mbind)
  )

;;;;;;;;;;;;;;;;;; the at_macro_expansion expander
;;;(AT_MACRO_EXPANSION  body...)
(defun mexpand_at_macro_expansion (sexpr env mexpander modctx)
  (debug "mexpand_at_macro_expansion sexpr=" sexpr "\n.. modctx" debug_less modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (modinienv (get_field :mocx_initialenv modctx))
	 (modmacroenv (get_field :mocx_macroenv modctx))
	 (maclist (get_field :mocx_macrolist modctx))
	 (curpair (pair_tail (list_first cont)))
	 (bodytup (expand_pairlist_as_tuple curpair modmacroenv mexpander modctx))
	 )
    (debug "mexpand_at_macro_expansion bodytup=" bodytup "\n.. modinienv=" modinienv "\n.. maclist=" maclist)
    (when (not (is_list maclist))
      (error_at loc "macros, i.e. AT_MACRO_EXPANSION, are forbidden in this module $1" 
		(get_field :mocx_modulename modctx))
      (return))
    (assert_msg "check bodytup" (is_multiple bodytup) bodytup)
    (foreach_in_multiple 
     (bodytup)
     (curbody :long bodix)
     (debug "mexpand_at_macro_expansion bodix#" bodix " curbody=" curbody)
     (list_append maclist curbody))
    (debug "mexpand_at_macro_expansion updated maclist=" maclist)
    (return ())
    ))
(install_initial_macro 'at_macro_expansion mexpand_at_macro_expansion)
(export_macro at_macro_expansion mexpand_at_macro_expansion
	      :doc #{The $AT_MACRO_EXPANSION macro will evaluate its
 body, e.g. containing @code{defun} or @code{definstance}
 at macro-expansion time. In particular, functions used
 inside a $DEFMACRO should be defined inside
 $AT_MACRO_EXPANSION and are not available in ordinary
 code.}#)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;; the defvar expander
;;;(DEFVAR varname [:doc documentation])
(defun mexpand_defvar (sexpr env mexpander modctx)
  (debug "mexpand_defvar sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (symbname (get_field :named_name symb))
	 (newenv (fresh_env env))
	 (docv ())
	 (vbind 
	  (instance class_variable_binding
		    :binder symb
		    ))
	 )
    (when (is_not_a symb class_symbol)
	(error_at loc "missing symbol for DEFVAR"_)
	(return))
    (warn_if_redefined symb env loc)
    (put_env env vbind)
    (setq curpair (pair_tail curpair))
      ;; handle the optional :doc documentationvalue
    (when (== (pair_head curpair) ':doc)
	    (setq curpair (pair_tail curpair)) ;; consume :doc
	    ;; the documentation is NOT macro-expanded
	    (setq docv (pair_head curpair))    ;; get the docv
	    (setq curpair (pair_tail curpair))  ;; consume it
	    )
    ;; check that no body is given
    (when curpair
      (error_at loc "DEFVAR too long - expecting (DEFVAR $1 [:doc <doc>])"
		  symbname)
      (return))
    (let ( (sdefvar (instance class_source_defvar
			      :loca_location loc 
			      :sdef_name symb
			      :sdef_doc docv
			      ))
	   )
      (debug "mexpand_defvar sdefvar=" sdefvar)
      (return sdefvar)
    )))
(install_initial_macro 'defvar mexpand_defvar)
(export_macro defvar mexpand_defvar
	      :doc #{The $DEFVAR macro defines a module variable,
initialized to the nil value. Syntax 
is ($DEFVAR @var{varame} [:doc @var{documentation}]).}#)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; the defhook expander
(defun mexpand_defhook (sexpr env mexpander modctx)
  (debug "mexpand_defhook sexpr=" sexpr " modctx=" modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (symbname (get_field :named_name symb))
	 (sycname (symbol_cname symb))
	 (intup ())			;formal input tuple
	 (outup ())			;formal output tuple
	 (restypkw ())			;the ctype keyword of result
	 (resctyp ())			;the ctype of result
	 (predefv ())			;optional :predef
	 (modvar ())			;optional :var
	 (docv ())			;optional :doc
	 (hbind (instance class_hook_binding
			  :binder symb
			  :hookbind_defhook ()
			  :hookbind_descr ())) ;to be filled later
	 (newenv (fresh_env env))
	 )
    (when (is_not_a symb class_symbol)
      (error_plain loc 
		   "missing symbol for (DEFHOOK <symb> <informals> <outformals> <ctype-key> [:predef <predef>] [:doc <doc>] <body....>)")
      (return))
    (when (>=i (string_length sycname)
	      (expr_chunk maxlen_chk :long #{/*mexpand_defhook $MAXLEN_CHK*/MELT_HOOKNAME_LEN}#))
      (error_at loc
		  "too long cname '$1' for symbol of DEFHOOK $2" sycname symbname)
      (return))
    (setq curpair (pair_tail curpair))
    (warn_if_redefined symb env loc)
    ;; parse the formal input arguments
    (setq intup 
	  (let ( (insexp (pair_head curpair))
		 )
	    (debug "mexpand_defhook insexp=" insexp)
	    (cond ( (is_a insexp class_sexpr)
		    (lambda_arg_bindings insexp :checkarg env mexpander modctx))
		  ( (null insexp)
		    (make_multiple discr_multiple 0))
		  (:else
		    (error_at 
		     loc
		     "bad input formals for  (DEFHOOK $1 <informals> <outformals> <ctype-key> ...)"
		     symbname)
		    (return)))))
    (debug "mexpand_defhook intup=" intup)
    (when (is_a intup  discr_variadic_formal_sequence)
      (error_at loc "DEFHOOK $1 cannot have variadic input formals" symbname)
      (return))
    (setq curpair (pair_tail curpair))
    ;; parse the formal output arguments
    (setq outup 
	  (let ( (outsexp (pair_head curpair))
		 )
	    (debug "mexpand_defhook outsexp=" outsexp)
	    (cond ( (is_a outsexp class_sexpr)
		    (lambda_arg_bindings outsexp :checkarg env mexpander modctx))
		  ( (null outsexp)
		    (make_multiple discr_multiple 0))
		  (:else
		    (error_at 
		     loc
		     "bad output formals for  (DEFHOOK $1 <informals> <outformals> <ctype-key> ...)"
		     symbname)
		    (return)))))
    (debug "mexpand_defhook outup=" outup)
    (when (is_a outup  discr_variadic_formal_sequence)
      (error_at loc "DEFHOOK $1 cannot have variadic output formals" symbname)
      (return))
    (setq curpair (pair_tail curpair))
    ;; parse the type keyword
    (setq restypkw (pair_head curpair))
    (when (is_not_a restypkw class_keyword)
      (error_at loc "DEFHOOK $1 needs a ctype keyword after output formals" symbname)
      (return))
    (let ( (cty (unsafe_get_field :symb_data restypkw))
	   )
      (when (is_not_a cty class_ctype)
      (error_at loc "DEFHOOK $1 with bad ctype keyword after output formals" symbname)
      (return))
      (setq resctyp cty))
    (setq curpair (pair_tail curpair))
    ;; handle :predef
    (when (== (pair_head curpair) ':predef)
      (setq curpair (pair_tail curpair))
      (if predefv (error_at loc "duplicate :predef in DEFHOOK $1" symbname))
      (setq predefv (pair_head curpair))
      (setq curpair (pair_tail curpair))
      )
    ;; handle :var
    (when (== (pair_head curpair) ':var)
      (setq curpair (pair_tail curpair))
      (if modvar (error_at loc "duplicate :VAR in DEFHOOK $1" symbname))
      (setq modvar (pair_head curpair))
      (setq curpair (pair_tail curpair))
      (when (is_not_a modvar class_symbol)
	(error_at loc "DEFHOOK $1 should have a symbol :VAR" symbname)
	(return))
      )
    ;; handle :doc
    (when (== (pair_head curpair) ':doc)
      (setq curpair (pair_tail curpair))
      (if docv (error_at loc "duplicate :doc in DEFHOOK $1" symbname))
      (setq docv (pair_head curpair))
      (setq curpair (pair_tail curpair))
      )
    ;; update the env & newenv
    (put_env env hbind)
    (foreach_in_multiple
     (intup)
     (inbnd :long inix)
     (warn_if_redefined (get_field :binder inbnd) env loc)
     (put_env newenv inbnd))
    (foreach_in_multiple
     (outup)
     (outbnd :long outix)
     (warn_if_redefined (get_field :binder outbnd) env loc)
     (put_env newenv outbnd))
    ;; parse the rest as to be expanded 
    (let ( (bodytup (expand_pairlist_as_tuple curpair newenv mexpander modctx)) 
	   (sdefhook
	    (instance class_source_defhook
		      :loca_location loc
		      :sdef_name symb
		      :sdef_doc docv
		      :sformal_args intup
		      :shook_out_formals outup
		      :shook_ctype resctyp
		      :shook_predef predefv
		      :shook_variable modvar
		      :shook_body bodytup
		      ))
	   )
      (put_fields hbind :hookbind_defhook sdefhook)
      (debug "mexpand_defhook result sdefhook=" sdefhook "\n hbind=" hbind)
      (return sdefhook)
      )))
(install_initial_macro 'defhook mexpand_defhook)
(export_macro defhook mexpand_defhook
 :doc #{The $DEFHOOK macro defines hooks, that is arbitrary C/C++
 routines coded in MELT.. Syntax is @code{(DEFHOOK @var{hook-name}
 @var{input-formals} @var{output-formals} @var{ctype} [:var
 @var{hook-var}] [:predef @var{hook-predef}] [:doc
 @var{documentation}] @var{body...})}. This binds @var{hook-name} to a
 generated hook value of $DISCR_HOOK discriminant, containing a
 pointer to the generated C/C++ routine and closed values, like
 functions and instances mentionned inside the @var{body}, etc... This
 generates an @code{extern "C"} C/C++ routine named
 @code{melthook_@var{hook-name}}, return a result of given @var{ctype},
 and with formal arguments: the hook value itself, the input formals,
 the pointers to output formals (which can be modified in the body
 with $SETQ).  If @var{hook-var} is given with a @code{:var}
 annotation, it should be a module variable defined with $DEFVAR, and
 that module variable is assigned to the hook value. Then, a C/C++
 routine named @code{melthookproc_@var{hook-name}} is emitted, taking
 only the input and output formals, and passing that module variable
 as the hook. And similarily for predefined hooks with their
 @var{hook-predef}.}#)







;;;;;;;;;;;;;;;;;; the define expander
;;;(DEFINE name [:doc documentation] expr ...)
 ;; same as defun, Scheme syntax sugar:
;;;(DEFINE (name formals...) [:doc documentation] expr ...)
(defun mexpand_define (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (curelem (pair_head curpair))
	 )
    (debug "mexpand_define start sexpr" sexpr)
    (cond 
     ;;
     ;; case (DEFINE name ...)
     ((is_a curelem class_symbol)
      (let ( 
	    (defname curelem)
	    (defdoc ())
	    (defvalbind (instance class_defined_value_binding
				  :binder defname
				  :defvalbind_define () ;filled below
				  ))
	    )
	(warn_if_redefined defname env loc)
	(put_env env defvalbind)
	(setq curpair (pair_tail curpair))
	;; consume the doc
	(if (== (pair_head curpair) ':doc)
	    (progn
	      (setq curpair (pair_tail curpair))
	      (setq defdoc (pair_head curpair))
	      (setq curpair (pair_tail curpair))))
	;;
	(let ( 
	      (bodytup (expand_pairlist_as_tuple curpair env mexpander modctx))
	      (sdefine (instance class_source_define
				 :loca_location loc
				 :sdef_name defname
				 :sdef_doc defdoc
				 :sdefine_body bodytup
				 ))
	      )
	  (put_fields defvalbind  :defvalbind_define sdefine)
	  (setq curpair (pair_tail curpair))
	  (debug "mexpand_define simple value bodytup=" bodytup " sdefine=" sdefine)
	  (return sdefine)
	  )))
     ;;
     ;; case (DEFINE (name formals ...) [:doc <docstr>] ...)
     ((is_a curelem class_sexpr)
      (let ( (floc (unsafe_get_field :loca_location curelem))
	     (fcont (unsafe_get_field :sexp_contents curelem))
	     (funame (pair_head (list_first fcont)))
	     (cursubpair (pair_tail (list_first fcont)))
	     (formaltup (lambda_arg_bindings cursubpair :checkarg env mexpander modctx))
	     (defdoc ())
	     (fbind (instance class_function_binding
			      :binder funame
			      :fubind_defun () ;to be filled later
			      ))
	     )
	;; check the funame
	(when (is_not_a funame class_symbol)
	  (error_at loc 
		    "Bad function name, expecting (DEFINE (name formals...) ...")
	  (return))
	(warn_if_redefined funame env loc)
	(put_env env fbind)
	;; consume the doc
	(when (== (pair_head curpair) ':doc)
	  (setq curpair (pair_tail curpair))
	  (setq defdoc (pair_head curpair))
	  (setq curpair (pair_tail curpair)))
	;;
	(let ( 
	      (newenv (fresh_env env))
	      (sdefun
	       (instance class_source_defun
			 :loca_location loc
			 :sdef_name funame
			 :sdef_doc defdoc
			 :sformal_args formaltup
			 :sfun_body ()	;filled later
			 ))
	      (formal0bind (multiple_nth formaltup 0))
	      )
	  ;; check that the first formal, if given, is a :value
	  (if formal0bind
	      (if (!= (get_field :fbind_type formal0bind) ctype_value)
		  (progn
		    (debug "mexpand_define function bad formal0bind=" formal0bind)
		    (error_at floc "invalid first formal argument in DEFINE-d function $1, expecting a :value"
			      (get_field :named_name funame))
		    (return))))
	  ;; bind the formals and expand the body
	  (foreach_in_multiple (formaltup) (fb :long fbix) (put_env newenv fb))
	  (let ( (bodytup (expand_pairlist_as_tuple curpair newenv mexpander modctx)) 
		 )
	    (put_fields sdefun :sfun_body bodytup)
	    (debug "mexpand_define function return sdefun" sdefun)
	    (return sdefun)
	    ))))
     ;;
     ;; bad DEFINE
     (:else
      (error_at loc "Expects <name> or (<name> <formals) after DEFINE")
      (return)
      ))
    ))

(install_initial_macro 'define mexpand_define)
(export_macro define mexpand_define
	      :doc #{The $DEFINE macro defines a named non-recursive
value.  Syntax (like in Scheme) is 
($DEFINE @var{name} [:doc @var{documentation}] @var{expr} ...) to define a value, and
($DEFINE (@var{funame} @var{formals}...) [:doc @var{documentation}]  @var{expr} ...) 
to define a function like $DEFUN does. Use $EXPORT_VALUES to make that name visible outside its module.}#)

;;;;;;;;;;;;;;;; the defclass expander

;; internal routine with multiple results to scan the defclass
(defun scan_defclass (sexpr env mexpander modctx)
  (let ( (predef ())
	 (supernam ())
	 (superbind ())
	 (superclass ())
	 (fieldnams ())
	 (docv ())
	 (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (fieldsloc ())
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (claname (get_field :named_name symb))
	 )
    (debug "scan_defclass sexpr" sexpr)
    (if (is_not_a symb class_symbol)
	(error_at loc "missing symbol for DEFCLASS"_))
    (setq curpair (pair_tail curpair))
    (forever scanloop
	     (if (not (is_pair curpair)) (exit scanloop))
	     (let ( (curkw (pair_head curpair)) )
	       (if (not (is_a curkw class_keyword)) 
		   (error_at loc "expecting keyword in DEFCLASS $1"_ claname))
	       (setq curpair (pair_tail curpair))
	       (let ( (curval (pair_head curpair)) )
		 (setq curpair (pair_tail curpair))
		 (cond 
		  ( (== curkw ':super)
		    (if supernam (error_at loc "duplicate super in DEFCLASS $1"_ claname))
		    (if (not (is_a curval class_symbol))
			(error_at loc "bad super in DEFCLASS $1"_ claname))
		    (setq supernam curval)
		    (debug "scan_defclass supernam" supernam)
		    (let ( (superb (find_env env supernam)) )
;;; should handle the case when the class is bound in the start environment
;;; to a value which happens to be a class
		      (cond ( (is_a superb class_class_binding)
			      (setq superbind superb) 
			      (setq superclass (unsafe_get_field :cbind_class superb))
			      )
			    ( (is_a superb class_value_binding)
			      (let ((superval (unsafe_get_field :vbind_value superb)))
				(if (is_a superval class_class)
				    (progn
				      (setq superbind superb)
				      (setq superclass superval)
				      )
				  (error_at loc "super $1 is not a class in DEFCLASS $2"_ 
					      (get_field :named_name supernam) claname)))
			      )
			    (:else 
			     (debug "scan_defclass superb=" superb " env" env)
			     (error_at loc "invalid super in DEFCLASS $1"_
					 (unsafe_get_field :named_name supernam))
			     )
			    )
		      ))
		  ( (== curkw ':fields)
		    (if fieldnams (error_at loc "duplicate fields in DEFCLASS $1"_ claname))
		    (if curval
			(if (is_not_a curval class_sexpr)
			    (error_at loc "bad fields in DEFCLASS $1"_ claname)))
		    (let ( (namlist (if curval (unsafe_get_field :sexp_contents curval)))
			   (namloc (if curval (unsafe_get_field :loca_location curval)))
			   (:long nbnam  (list_length namlist))
			   (:long ix 0)
			   (nampair (list_first namlist))
			   (namtupl (make_multiple discr_multiple nbnam)) )
		      (setq fieldsloc namloc)
		      (forever namloop
			       (if (not (is_pair nampair)) (exit namloop))
			       (let ( (curnam (pair_head nampair)) )
				 (if (not (is_a curnam class_symbol))
				     (error_at namloc "non name field #$1 in DEFCLASS $2"_ (+i ix 1) claname))
				 (multiple_put_nth namtupl ix curnam)
				 )
			       (setq nampair (pair_tail nampair))
			       (setq ix (+i ix 1))
			       )
		      (setq fieldnams namtupl)
		      ))
		  ( (== curkw ':predef)
		    (if predef (error_at loc "duplicate predef in DEFCLASS $1"_ claname))
		    (setq predef (mexpander curval env mexpander modctx))
		    (cond
		     ( (is_integerbox predef) 
		       ()
		       )
		     ( (is_a predef class_symbol)
		       ()
		       )
		     (:else
		      (error_at loc "bad predef in DEFCLASS $1"_ claname)
		      )
		     )
		    )
		  ( (== curkw ':doc)
		    (if docv (error_at loc "duplicate doc in DEFCLASS $1"_ claname))
		    ;; the documentation is NOT macro-expanded!
		    (setq docv curval)
		    )
		  (:else
		   (error_at loc "invalid keyword $1 in DEFCLASS $2"_ 
			       (unsafe_get_field :named_name curkw) claname)
		   )
		  ))))
    (debug "scan_defclass returns symb=" symb " loc=" loc)
    (debug "scan_defclass returns supernam=" supernam " superbinds=" superbind " superclass=" superclass)
    (debug "scan_defclass returns predef=" predef " fieldnams=" fieldnams " fieldsloc=" fieldsloc)
    (debug "scan_defclass returns docv" docv)
    (warn_if_redefined symb env loc)
    (return symb loc supernam superbind superclass predef fieldnams fieldsloc docv)
    ))


(defun mexpand_defclass (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (debug "mexp.defclass sexpr" sexpr)
  (multicall 
   (symb loc supernam superbind superclass predef fieldnams fieldsloc docv)
   (scan_defclass sexpr env mexpander modctx)
   (debug "mexp.defclass scanned symb=" symb" loc=" loc)
   (debug "mexp.defclass scanned supernam=" supernam " superbind=" superbind " superclass=" superclass)
   (debug "mexp.defclass scanned predef=" predef)
   (debug "mexp.defclass scanned fieldnams=" fieldnams " fieldsloc=" fieldsloc)
   (debug "mexp.defclass scanned docv=" docv)
   (assert_msg "check symb" (is_a symb class_symbol) symb)
   (let ( (claname (get_field :named_name symb))
	  )
     (and (null predef)
	  (null superclass)
	  (error_at loc 
		    "DEFCLASS $1 of a non-predefined class without superclass"
		    claname)
	  )
     (let ( 
	   (ancestors (if (is_object superclass)
			  (let ( (superancestors (unsafe_get_field :class_ancestors superclass))
				 (:long nbsuperanc (multiple_length superancestors))
				 (anctuple (make_multiple discr_class_sequence (+i 1 nbsuperanc)))
				 (:long ix 0)
				 )
			    (assert_msg "check superclass" (is_a superclass class_class) superclass)
			    (assert_msg "check superancestors" (is_multiple superancestors) superancestors)
			    (forever ancloop
				     (if (>=i ix nbsuperanc) (exit ancloop))
				     (multiple_put_nth anctuple ix (multiple_nth superancestors ix))
				     (setq ix (+i ix 1))
				     )
			    (multiple_put_nth anctuple nbsuperanc superclass)
			    anctuple
			    )
			(make_multiple discr_class_sequence 0)))
	   (superfields (if (is_object superclass)
			    (unsafe_get_field :class_fields superclass)))
	   (:long nbsuperfields (multiple_length superfields))
	   (:long nbfieldnames (multiple_length fieldnams))
	   (boxnbsuperfields (make_integerbox discr_integer nbsuperfields))
	   (fieldstrmap (make_mapstring discr_map_strings (+i 3 (*i 2 (+i nbsuperfields nbfieldnames)))))
	   (fieldtup (make_multiple discr_field_sequence (+i nbsuperfields nbfieldnames)))
	   (ownfieldbindings (make_multiple discr_multiple nbfieldnames))
	   (newclass (instance class_class
			       :named_name (unsafe_get_field :named_name symb)
			       :class_ancestors ancestors
			       ;; other fields to be set later
			       ))
	   (clabind (instance class_class_binding
			      :binder symb
			      :cbind_class newclass))
	   )
       (put_env env clabind)
       (debug "expdefclas superfields" superfields)
       (foreach_in_multiple 
	(superfields)
	(sfld :long ix)
	(assert_msg "check superfield" (is_a sfld class_field) sfld)
	(multiple_put_nth fieldtup ix sfld)
	(mapstring_putstr fieldstrmap (unsafe_get_field :named_name sfld) sfld)
	)
;;;
       (foreach_in_multiple
	(fieldnams)
	(fldnam :long ix)
	(assert_msg "check fldnam" (is_a fldnam class_symbol))
	(let ( (fldstr (unsafe_get_field :named_name fldnam)) 
	       (fldprevbind (find_env env fldnam))
	       )
	  (if (mapstring_getstr fieldstrmap fldstr)
	      (error_at fieldsloc "duplicate field $1 in DEFCLASS $2"_ fldstr claname))
	  (cond
	   ( (null fldprevbind)
	     (void)
	     )
	   ( (is_a fldprevbind class_field_binding)
	     (debug "mexpand_defclass fldprevbind !field" fldprevbind)
	     (error_at fieldsloc "field name $1 already defined in DEFCLASS $2"_ fldstr claname)
	     )
	   ( (is_a fldprevbind class_value_binding)
	     (debug "mexpand_defclass fldprevbind !value" fldprevbind)
	     (debug "mexpand_defclass symb !value" symb)
	     (let ( (prevalue (get_field :vbind_value fldprevbind))
		    )
	       ;; this test avoids warnings when recompiling
	       ;; warmelt-*.melt files
	       (if (or (is_not_a prevalue class_field)
		       (!=s (get_field :named_name (get_field :fld_ownclass prevalue))
			    (get_field :named_name symb)))
		   (warning_at fieldsloc "field name $1 already bound to a value in DEFCLASS $2"_ fldstr claname)
		 )))
	   (:else
	    (debug "mexpand_defclass fldprevbind !other" fldprevbind)
	    (warning_at  fieldsloc "field name $1 previously bound in DEFCLASS $2"_ fldstr claname))
	   )
	  (let ( (:long fldoff (+i ix (get_int boxnbsuperfields))) 
		 (newfld (instance class_field
				   :named_name fldstr
				   :fld_ownclass newclass
				   )) )
	    (put_int newfld fldoff)
					;(messagenum_dbg "expdefclafldnam fldoff" fldoff)
	    (multiple_put_nth fieldtup fldoff newfld)
	    (mapstring_putstr fieldstrmap fldstr newfld)
	    (let ( (newfldbind (instance class_field_binding
					 :binder fldnam
					 :flbind_clabind clabind
					 :flbind_field newfld)) )
	      (warn_if_redefined fldnam env loc)
	      (put_env env newfldbind)
	      (multiple_put_nth ownfieldbindings ix newfldbind)
	      )
	    )))
       (unsafe_put_fields newclass
			  :class_fields fieldtup)
       ;; we need to put the object magic to MELTOBMAG_OBJECT now
       (code_chunk setobjmagic
		   #{((meltobject_ptr_t)$newclass)->obj_num = MELTOBMAG_OBJECT ;
		   }#)
       (debug "mexp.defclass newclass=" newclass)
       (instance class_source_defclass
		 :loca_location loc
		 :sdef_name symb
		 :sdef_doc docv
		 :sobj_predef predef
		 :sclass_clabind clabind
		 :sclass_superbind superbind
		 :sclass_fldbinds ownfieldbindings
		 )))))
(install_initial_macro 'defclass mexpand_defclass)
(export_macro defclass mexpand_defclass
	      :doc #{The $DEFCLASS macro defines a class. Syntax
is (DEFCLASS symbol [:doc documentation] :super super-class :fields
fields-list). Conventionally, the class name (i.e. the symbol) should
preferably start with CLASS_. The fields' names should preferably be
globally unique, and usually share a common prefix. See also
$CLASS_ROOT $CLASS_CLASS $CLASS_FIELD etc.}#)



;;;;;;;;;;;;;;;; the definstance expander

;; internal to parse a field assignment in a given class (or without class, for put_field)
(defun parse_field_assignment (cla loc fldkw expr env mexpander modctx)
  (debug "start parse_field_assignment cla" cla)
  (debug "start parse_field_assignment loc" loc)
  (debug "start parse_field_assignment fldkw" fldkw)
  (when (is_not_a fldkw class_keyword)
	(error_plain loc "expecting :fieldname in field assignment"_)
	(return)
	)
  (assert_msg "check fldkw" (is_a fldkw class_keyword) fldkw)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  ;; expr is an sexpr or a symbol or a string or ...
  (let ( (fld ()) 
	 (fldkwnam (get_field :named_name fldkw))
	 )
    ;; if we have a class, find the field inside
    (if (is_a cla class_class)
	(let ( (clafields (unsafe_get_field :class_fields cla)) 
	       )
	  (debug "parse_field_assignment clafields" clafields)
	  (multicall 
	   (foundfld :long ix :value foundname)
	   (multiple_iterate_test
	    clafields
	    (lambda (curfld :long ix)
	      (assert_msg "check fld" (is_a curfld class_field) fld)
	      (let ( (curfldnam  (unsafe_get_field :named_name curfld)) )
		(cond
		 ;; found the field, so return nil & the fieldname
		 ( (==s curfldnam
			(unsafe_get_field :named_name fldkw))
		   (debug "parse_field_assignment found curfld" curfld)
		   (debug "parse_field_assignment found curfldnam" curfldnam)
		   (return () curfldnam))
		 (:else
		  ;; did not found the field, so return true
		  (return :true ()))))))
	   (if foundfld
	       (progn
		 (debug "parse_field_assignment return foundfld" foundfld)
		 (setq fld foundfld))))))
    (debug "parse_field_assignment after class scanning fld" fld)
    (if (null fld)
	;; othewise, find the field by its bound name
	(let ( 
	       (fldnam (create_symbolstr fldkwnam)) 
	       )
	  (debug "parse_field_assignment fldnam" fldnam)
	  (assert_msg "check fldnam symb" (is_a fldnam class_symbol) fldnam)
	  (let ( (fldbind (find_env env fldnam)) )
	    (debug "parse_field_assignment fldbind" fldbind)
	    (cond 
	     ( (null fldbind)
	       (error_at loc "unknown field name $1 in field assignment"_ 
			   fldkwnam)
	       (return)
	       )
	     ( (is_a fldbind class_field_binding)
	       (setq fld (unsafe_get_field :flbind_field fldbind) )
	       (debug "parse_field_assignment found fld in field binding" fld)
	       )
	     ( (is_a fldbind class_value_binding)
	       (let ( (vfld (unsafe_get_field :vbind_value fldbind)) )
		 (debug "parse_field_assignment has vfld" vfld)
		 (if (is_a vfld class_field)
		     (let ( (vfldnam  (unsafe_get_field :named_name vfld))
			    (kwnam (unsafe_get_field :named_name fldkw)) 
			    )
		       (setq fld vfld)
		       (when (!=s vfldnam kwnam)
			 ;; this happen when a field is used by its synonym
			 (warning_at loc "obsolete use of synonym field $1, better use $2 " kwnam vfldnam))
			 (debug "parse_field_assignment gives vfld" vfld)
		       vfld)) ))
	     (:else
	      (error_at loc "bad field name $1 in field assignment"_
			  fldkwnam)
	      (return)
	      ))
	    (debug "parse_field_assignment fld from environment" fld)
	    )))			  
    ;;end when fld has to be found in the environment
    (assert_msg "check fld" (is_a fld class_field) fld)
    (let ( (xex (mexpander expr env mexpander modctx)) 
	   (fa (instance class_source_fieldassign 
			 :loca_location loc
			 :sfla_field fld
			 :sfla_expr xex
			 ))
	   )
      (debug "parse_field_assignment return fa" fa)
      (return fa))
    ))

;; the definstance expanser
(defun mexpand_definstance (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (debug "mexp.definstance sexpr" sexpr)
  (let ( (predef ())
	 (objnum ())
	 (fields ())
	 (fieldnams ())
	 (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (claname ())
	 (cla ())
	 (clabind ())
	 (docv ())
	 )
    (if (is_not_a symb class_symbol)
	(error_at loc "missing symbol for DEFINSTANCE"_))
    (setq curpair (pair_tail curpair))
    (let ( 
	  (symbname (get_field :named_name symb))
	  (nam (pair_head curpair)) 
	  (ibind 
	   (instance class_instance_binding
		     :binder symb
		     :ibind_iclass (); filled later
		     ))
	  )
      (warn_if_redefined symb env loc)
      (put_env env ibind)
      (if (is_not_a nam class_symbol)
	  (error_at loc "missing class name for DEFINSTANCE $1"_ symbname))
      (let ( (bnd (find_env env nam)) 
	     (fldlist (make_list discr_list))
	     )
	(cond 
	 ( (is_a bnd class_class_binding)
	   (setq clabind bnd)
	   (setq cla (unsafe_get_field :cbind_class bnd)) )
	 ( (and (is_a bnd class_value_binding)
		(is_a (unsafe_get_field :vbind_value bnd) class_class))
	   (setq clabind bnd)
	   (setq cla (unsafe_get_field :vbind_value bnd)))
	 (:else
	  (error_at loc "invalid class name $1 for DEFINSTANCE $2"_
		      (unsafe_get_field :named_name nam) symbname)
	  (return ())
	  ))
	(setq claname nam)
	(assert_msg "check cla" (is_a cla class_class) cla)
	(setq curpair (pair_tail curpair))
	(forever insloop
		 (if (not (is_pair curpair)) (exit insloop))
		 (let ( (curfkw (pair_head curpair)) )
		   (if (is_not_a curfkw class_keyword)
		       (error_at loc "expecting keyword in DEFINSTANCE $1"_ symbname))
		   (setq curpair (pair_tail curpair))
		   (let ( (curexp (pair_head curpair)) )
		     (cond  ( (== curfkw ':obj_num)
			      (if objnum (error_at loc "duplicate :obj_num in DEFINSTANCE $1"_ symbname))
			      (setq objnum 
				    (if (is_a curexp class_sexpr)
					(mexpander curexp env mexpander modctx)
				      curexp))
			      )
			    ( (== curfkw ':predef)
			      (if predef (error_at loc "duplicate :predef in DEFINSTANCE $1"_ symbname))
			      (setq predef 
				    (if (is_a curexp class_sexpr)
					(mexpander curexp env mexpander modctx)
				      curexp))
			      )
			    ( (== curfkw ':doc)
			      (if docv (error_at loc "duplicate :doc in DEFINSTANCE $1"_ symbname))
			      (setq docv curexp)
			      )
			    (:else 
			     (let  ( (flda 
				      (parse_field_assignment cla loc curfkw curexp env mexpander modctx)) )
			       (if flda 
				   (list_append fldlist flda)
				 )
			       ))))
		   (setq curpair (pair_tail curpair))
		   ))
	(let ( (fastup (list_to_multiple fldlist discr_multiple)) 
	       (sinst 
		(instance class_source_definstance
			  :loca_location loc
			  :sdef_name symb
			  :sdef_doc docv
			  :sobj_predef predef
			  :sinst_class cla
			  :sinst_clabind clabind
			  :sinst_objnum objnum
			  :sinst_fields fastup
			  ))
	       )
	  (put_fields ibind :ibind_iclass cla)
	  (debug "mexp.definstance sinst" sinst)
	  (return sinst)
	  )))))
(install_initial_macro 'definstance mexpand_definstance)
(export_macro definstance mexpand_definstance
 :doc #{The $DEFINSTANCE syntax defines a static instance bound by a
 symbol. Syntax is (DEFINSTANCE <symbol> <class> [:doc documentation]
 @{:<field> <value>@}*). The symbol is bound to the newly made
 instance.}#)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;; the defselector expanser
(defun mexpand_defselector (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (debug "mexp.definstance sexpr" sexpr)
  (let ( (predef ())
	 (objnum ())
	 (fields ())
	 (fieldnams ())
	 (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (symb (pair_head curpair))
	 (claname ())
	 (cla ())
	 (docv ())
	 (clabind ())
	 (formals ())
	 )
    (when (is_not_a symb class_symbol)
	  (error_at loc "missing symbol for (DEFSELECTOR <name> <class> ...)"_)
	  (return))
    (setq curpair (pair_tail curpair))
    (let (
	  (symbname (get_field :named_name symb))
	  (nam (pair_head curpair)) 
	  (selbind (instance class_selector_binding
			      :binder symb
			      :sbind_selectordef (); filled later
			      ))
	   )
      (when (is_not_a nam class_symbol)
	(error_at loc "missing class name for (DEFSELECTOR $1 <class> ...)"_ symbname)
	(return))
      (warn_if_redefined symb env loc)
      (put_env env selbind)
      ;;
      (setq claname nam)
      (debug "mexpand_defselector claname" claname)
      (let ( (bnd (find_env env claname)) 
	     (fldlist (make_list discr_list))
	     )
	(cond 
	 ( (is_a bnd class_class_binding)
	   (setq clabind bnd)
	   (setq cla (unsafe_get_field :cbind_class bnd)) )
	 ( (and (is_a bnd class_value_binding)
		(is_a (unsafe_get_field :vbind_value bnd) class_class))
	   (setq clabind bnd)
	   (setq cla (unsafe_get_field :vbind_value bnd)))
	 ((notnull bnd)
	  (debug "mexpand_defselector faulty bnd" bnd)
	  (error_at loc "invalid class name $1 for (DEFSELECTOR $2 <class> ...)"_
		      (unsafe_get_field :named_name claname) symbname)
	  (return))
	 (:else
	  (error_at loc "unknown class name $1 for (DEFSELECTOR $2 <class> ...)"_
		      (unsafe_get_field :named_name claname) symbname)
	  (return)
	  ))
	;;
	(debug "mexpand_defselector cla" cla)
	(when (not (subclass_or_eq cla class_selector))
	  (debug "mexpand_defselector class_selector=" class_selector)
	  (error_at loc "invalid class $1 in (DEFSELECTOR $2 <class>); expecting CLASS_SELECTOR or its subclass"_
		    (unsafe_get_field :named_name claname) symbname)
	  (return))
	;;
	(assert_msg "check cla" (is_a cla class_class) cla)
	(setq curpair (pair_tail curpair))
	(forever insloop
		 (if (not (is_pair curpair)) (exit insloop))
		 (let ( (curfkw (pair_head curpair)) )
		   (if (is_not_a curfkw class_keyword)
		       (error_at loc "expecting keyword in DEFSELECTOR $1"_ symbname))
		   (setq curpair (pair_tail curpair))
		   (let ( (curexp (pair_head curpair)) )
		     (cond  ( (== curfkw ':obj_num)
			      (if curexp (error_at loc "duplicate :obj_num in DEFSELECTOR $1"_ symbname))
			      (setq objnum 
				    (if (is_a curexp class_sexpr)
					(mexpander curexp env mexpander modctx)
				      curexp))
			      )
			    ( (== curfkw ':predef)
			      (if curexp (error_at loc "duplicate :predef in DEFSELECTOR $1"_ symbname))
			      (setq predef 
				    (if (is_a curexp class_sexpr)
					(mexpander curexp env mexpander modctx)
				      curexp))
			      )
			    ( (== curfkw ':doc)
			      (if docv (error_at loc "duplicate :doc in DEFSELECTOR $1"_ symbname))
			      (setq docv curexp)
			      )
			    ( (== curfkw ':formals)
			      (if formals (error_at loc "duplicate :formals in DEFSELECTOR $1"_ symbname))
			      ;; curfkw is non-null so we ask the
			      ;; arguments to be checked by
			      ;; lambda_arg_bindings
			      (setq formals (lambda_arg_bindings curexp :checkarg env mexpander modctx))
			      (let ( (firstf (multiple_nth formals 0)) )
				(cond
				 ( (null firstf)
				   (error_at loc 
					     ":formals of DEFSELECTOR $1 should have at least one value argument for the receiver"_ 
					     symbname))
				 ( (!= (get_field :fbind_type firstf) ctype_value)
				   (error_at loc "first :formals of DEFSELECTOR $1 should be a :value"_ symbname))
			      )))
			    (:else 
			     (let  ( (flda (parse_field_assignment cla loc curfkw curexp env mexpander modctx)) )
			       (if flda 
				   (list_append fldlist flda)
				 )
			       ))))
		   (setq curpair (pair_tail curpair))
		   ))
	(let ( ( fastup (list_to_multiple fldlist discr_multiple)) 
	       (res (instance class_source_defselector
			      :loca_location loc
			      :sdef_name symb
			      :sobj_predef predef
			      :sinst_class cla
			      :sinst_clabind clabind
			      :sinst_objnum objnum
			      :sinst_fields fastup
			      :sdefsel_formals formals
			      ))
	       )
	  (put_fields selbind :sbind_selectordef res)
	  res
	  )))))
(install_initial_macro 'defselector mexpand_defselector)
(export_macro defselector mexpand_defselector
 :doc #{The $DEFSELECTOR syntax defines a selector for sending
messages. Syntax is (DEFSELECTOR <symbol> <selector-class> [:doc
<documentation>] [:formals ( <formals>...)]).}#)



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; the [make_]instance expander
(defun mexpand_instance (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (fields ())
	 (fieldnams ())
	 (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (clasymb (pair_head curpair))
	 (cla ())
	 (clabind ())
	 )
    (debug "mexpand_instance start sexpr" sexpr)
    (if (is_not_a clasymb class_symbol)
	(error_plain loc "missing class symbol for INSTANCE"_))
    (let ( (bnd (find_env env clasymb)) 
	   (fldlist (make_list discr_list))
	   (claname (get_field :named_name clasymb))
	   )
      (cond 
       ( (is_a bnd class_class_binding)
	 (setq clabind bnd)
	 (setq cla (unsafe_get_field :cbind_class bnd)) 
	 )
       ( (and (is_a bnd class_value_binding)
	      (is_a (unsafe_get_field :vbind_value bnd) class_class))
	 (setq clabind bnd)
	 (setq cla (unsafe_get_field :vbind_value bnd))
	 )
       (:else
	(error_at loc "invalid class name for INSTANCE $1"_
		    claname)
	(return ())
	))
      (debug "mexpand_instance cla" cla)
      (assert_msg "check cla" (is_a cla class_class) cla)
      (setq curpair (pair_tail curpair))
      (forever insloop
	       (if (not (is_pair curpair)) (exit insloop))
	       (let ( (curfkw (pair_head curpair)) )
		 (if (is_not_a curfkw class_keyword)
		     (error_at loc "expecting keyword in INSTANCE $1"_ claname))
		 (setq curpair (pair_tail curpair))
		 (let ( (curexp (pair_head curpair)) )
		   (let  ( (flda 
			    (parse_field_assignment cla loc curfkw curexp env mexpander modctx)) )
		     (debug "mexpand_instance flda" flda)
		     (if flda 
			 (list_append fldlist flda)
		       (error_at loc "bad field name $1 in INSTANCE $2"_
				   (unsafe_get_field :named_name curfkw) claname)
		       ))))
	       (setq curpair (pair_tail curpair))
	       )
      (let ( ( fastup (list_to_multiple fldlist discr_multiple)) )
	(instance class_source_instance
		  :loca_location loc
		  :smins_class cla
		  :smins_clabind clabind
		  :smins_fields fastup)
	))))
(install_initial_macro 'instance mexpand_instance)
(export_macro instance mexpand_instance
 :doc #{The $INSTANCE syntax is for making new objects. Syntax
 is (INSTANCE <class> @{:<field> <expression>@}*).}#)



;;;; the load expander should return the tuple of expanded stuff read from the file
(defun mexpand_load (sexpr env mexpander modctx)
  (debug "mexpand_load start sexpr=" sexpr "\n.. env=" env)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (shortbacktrace_dbg "mexpand_load" 25)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (filnam (pair_head curpair))
	 )
    (if (pair_tail curpair)
	(error_plain loc "LOAD expects one argument"))
    (if (is_a filnam class_sexpr)
	(setq filnam (mexpander filnam env mexpander modctx)))
    (if (is_a filnam class_named)
	(setq filnam (unsafe_get_field :named_name filnam)))
    (debug "mexpand_load" " loc=" loc "; filnam=" filnam)
    (cond 
     ( (is_string filnam)
       (inform_strv loc "MELT loading file " filnam)
       (let ( (curead (read_file filnam)) )
	 (debug "mexpand_load"" curead=" curead)
	 (let ( (explist (macroexpand_toplevel_list curead env mexpander modctx)) 
		(exptuple (list_to_multiple explist discr_multiple))
		)
	   (debug "mexpand_load" " explist=" explist)	   
	   (shortbacktrace_dbg "mexpand_load" 10)
	   (debug "mexpand_load" " return exptuple=" exptuple)
	   (return exptuple)
	   )
	 )
       )
     (:else
      (debug "mexpand_load strange filnam" filnam)
      (error_plain loc "LOAD expects a string filename")))
    ))
(install_initial_macro 'load mexpand_load)
(export_macro load mexpand_load
 :doc #{The $LOAD macro is for reading expressions from another
 file. Syntax is (LOAD <file-name>).}#)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mexpand_skip_nil (sexpr env mexpander modctx)
  (debug "mexpand_skip_nil" " start sexpr=" sexpr "\n.. env=" env)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (reslist (make_list discr_list))
	 (explist (expand_restlist_as_tuple cont env mexpander modctx))
	 )
    (each_component_in_list
     explist
     curcomp
     (debug "mexpand_skip_nil" " curcomp=" curcomp)
     (if curcomp (list_append reslist curcomp))
     )
    (let (
	  (restup (list_to_multiple reslist discr_multiple))
	  )
      (debug "mexpand_skip_nil" " restup=" restup)
      (return restup)
      )
    )
  )
(install_initial_macro 'skip_nil mexpand_skip_nil)
(export_macro skip_nil mexpand_skip_nil
	      :doc #{The $SKIP_NIL macro is macro-expanding its arguments, and skipping those who are macro-expanded to nil.}#
	      )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; parse a field pattern
(defun parse_field_pattern (fkeyw cla flpsexp env pctx psloc)
  (debug "parse_field_pattern keyw" fkeyw)
  (assert_msg "check fkeyw" (is_a fkeyw class_keyword) fkeyw)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctc" (is_a pctx class_pattern_expansion_context) pctx)
  (assert_msg "check cla" (is_a cla class_class) cla)
  (let (
	(clafields (unsafe_get_field :class_fields cla))
	(fldcont (instance class_reference :referenced_value ())) 
	(flpat (patternexpand_1 flpsexp env pctx psloc)) 
	)
    (debug "parse_field_pattern clafields" clafields)
    ;; find the field inside the class
    (multiple_iterate_test
     clafields
     (lambda (cfld :long ix)
       (assert_msg "check fld" (is_a cfld class_field) cfld)
       (if (==s (unsafe_get_field :named_name cfld) 
		(unsafe_get_field :named_name fkeyw))
	   (progn 
	     (put_fields fldcont :referenced_value cfld)
	     (return ()	())			; nil to exit to iteration 
	     )
	 (return cfld ())))
     )
    (let ( (fld (get_field :referenced_value fldcont))
	   )
      (when (is_not_a fld class_field)
	    (debug "parse_field_pattern bad fld" fld)
	    (error_at psloc "invalid :field $1 in pattern"
			(unsafe_get_field :named_name fkeyw))
	    (return))
      (let (
	    (patf (instance class_source_field_pattern
			    :loca_location psloc
			    :spaf_field fld
			    :spaf_pattern flpat
			    ))
	    )
	(debug "parse_field_pattern return patf" patf)
	(return patf)
	))))

(defun patexpand_instance (sexpr env pctx)
  (debug "patexpand_instance sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(fields ())
	(fieldnams ())
	(curpair (pair_tail (list_first cont)))
	(clasymb (pair_head curpair))
	(cla ())
	(clabind ())
	)
    (if (is_not_a clasymb class_symbol)
	(error_plain loc "missing class symbol for INSTANCE pattern"_))
    (let ( (bnd (find_env env clasymb)) 
	   (fldlist (make_list discr_list))
	   (claname (get_field :named_name clasymb))
	   )
      (cond 
       ( (is_a bnd class_class_binding)
	 (setq clabind bnd)
	 (setq cla (unsafe_get_field :cbind_class bnd)) 
	 )
       ( (and (is_a bnd class_value_binding)
	      (is_a (unsafe_get_field :vbind_value bnd) class_class))
	 (setq clabind bnd)
	 (setq cla (unsafe_get_field :vbind_value bnd))
	 )
       (:else
	(error_at loc "invalid class name for INSTANCE $1"_
		    claname)
	(return ())
	))
      (assert_msg "check cla" (is_a cla class_class) cla)
      (setq curpair (pair_tail curpair))
      ;; build the list of field patterns
      (forever 
       insloop
       (if (not (is_pair curpair)) (exit insloop))
       (let ( (curfkw (pair_head curpair)) )
	 (if (is_not_a curfkw class_keyword)
	     (error_plain loc "expecting keyword in INSTANCE"_))
	 (setq curpair (pair_tail curpair))
	 (let ( (curexp (pair_head curpair)) )
	   (let  ( (fldp (parse_field_pattern curfkw cla curexp env pctx loc)) )
	     (debug "patexpand_instance fldp" fldp)
	     (if fldp
		 (list_append fldlist fldp)
	       (error_at loc "bad field name $1 in INSTANCE $2"_
			 (unsafe_get_field :named_name curfkw) claname)
	       ))))
       (setq curpair (pair_tail curpair))
       )
      (let (
	    (spatfields  (list_to_multiple fldlist discr_multiple))
	    (subpats (multiple_map spatfields 
				   (lambda (curpatfld :long curix)
				     (get_field :spaf_pattern curpatfld))))
	    (spati (instance class_source_pattern_instance
			      :loca_location loc
			      :pat_weight () ;; set below
			      :spat_class cla
			      :spat_fields  spatfields))
	     )
	(multicall 
	 (subpatw :long imax imin isum)
	 (pattern_weight_tuple subpats)
	 (unsafe_put_fields 
	  spati 
	  :pat_weight 
	  (make_integerbox discr_constant_integer (+i 1 isum)))
	 )
	(debug "patexpand_instance return spati" spati)
	(return spati)
	))
    ))
(install_initial_patmacro 'instance patexpand_instance mexpand_instance)
(export_patmacro instance patexpand_instance mexpand_instance
:doc #{The $INSTANCE pattern macro matches an instance when used as a
pattern, or creates an instance when used as an expression.  Pattern
syntax is ?($INSTANCE @var{class-name} @var{:field1} @var{pattern1}
@var{:field2} @var{pattern2}...) - there can be zero, one or more
distinct fields. A value matches such a pattern if the value is an
instance of @var{class-name} or a sub-class and if each specified
field matches its [sub-]pattern. Expression syntax is ($INSTANCE
@var{class-name} @var{:field1} @var{value1} @var{:field2}
@var{value2}...). All the fields should be acceptable for the
specified @var{class-name}. In expressions, missing fields are
initialized to nil. In patterns missing fields are not matched. The
given @var{class-name} is a fixed class (not a variable) possessing
all the specified fields.}# )

(defun patexpand_object (sexpr env pctx)
  (debug "patexpand_object sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(fields ())
	(fieldnams ())
	(curpair (pair_tail (list_first cont)))
	(clasymb (pair_head curpair))
	(cla ())
	(clabind ())
	)
    (if (is_not_a clasymb class_symbol)
	(error_plain loc "missing class symbol for  OBJECT pattern"_))
    (let ( (bnd (find_env env clasymb)) 
	   (fldlist (make_list discr_list))
	   (claname (get_field :named_name clasymb))
	   )
      (cond 
       ( (is_a bnd class_class_binding)
	 (setq clabind bnd)
	 (setq cla (unsafe_get_field :cbind_class bnd)) 
	 )
       ( (and (is_a bnd class_value_binding)
	      (is_a (unsafe_get_field :vbind_value bnd) class_class))
	 (setq clabind bnd)
	 (setq cla (unsafe_get_field :vbind_value bnd))
	 )
       (:else
	(error_strv loc "invalid class name for OBJECT $1 pattern"_
		    claname)
	(return ())
	))
      (assert_msg "check cla" (is_a cla class_class) cla)
      (setq curpair (pair_tail curpair))
      ;; build the list of field patterns
      (forever 
       insloop
       (if (not (is_pair curpair)) (exit insloop))
       (let ( (curfkw (pair_head curpair)) )
	 (if (is_not_a curfkw class_keyword)
	     (error_at loc "expecting keyword in OBJECT $1 pattern"_ claname))
	 (setq curpair (pair_tail curpair))
	 (let ( (curexp (pair_head curpair)) )
	   (let  ( (fldp (parse_field_pattern curfkw cla curexp env pctx loc)) )
	     (debug "patexpand_object fldp" fldp)
	     (if fldp
		 (list_append fldlist fldp)
	       (error_at loc "bad field name $1 in OBJECT $2 pattern"_
			   (unsafe_get_field :named_name curfkw) claname)
	       ))))
       (setq curpair (pair_tail curpair))
       )
      (let ( 
	    (patfields  (list_to_multiple fldlist discr_multiple))
	    (subpats (multiple_map patfields
				   (lambda (curpatfld :long ix)
				     (get_field  :spaf_pattern curpatfld))))
	    (spati (instance class_source_pattern_object
			      :loca_location loc
			      :spat_class cla
			      :spat_fields patfields))
	     )
	(multicall 
	 (subpatw :long imax imin isum)
	 (pattern_weight_tuple subpats)
	 (unsafe_put_fields 
	  spati 
	  :pat_weight 
	  (make_integerbox discr_constant_integer (+i 1 isum)))
	(debug "patexpand_object return spati" spati)
	(return spati)
	)))
    ))

(defun mexpand_object (sexpr env mexpander modctx)
  (debug "mexpand_object sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let (
	(loc  (unsafe_get_field :loca_location sexpr))
	)
    (error_plain loc "OBJECT cannot be macro-expanded in expression context - use INSTANCE instead")
    (return)
))

(install_initial_patmacro 'object patexpand_object mexpand_object)
(export_patmacro object patexpand_object mexpand_object
		 :doc #{The $OBJECT pattern macro matches an instance
when used as a pattern.  Pattern syntax is ?($OBJECT @var{class-name}
@var{:field1} @var{pattern1} @var{:field2} @var{pattern2}...) - there
can be zero, one or more distinct fields. A value matches such a
pattern if the value is an instance of @emph{exactly}
@var{class-name} (not a sub-class) and if each specified field matches
its [sub-]pattern.  The $OBJECT pattern macro should not be used in
expression context.  See also $INSTANCE and $DEFCLASS.}# )



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun expand_macrostring_pairs (pairs sloc env mexpander modctx)
  (debug "expand_macrostring_pairs pairs=" pairs)
  (assert_msg "check pairs" (is_pair pairs) pairs)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (chklist (make_list discr_list))
	 )
    (letrec ( 
	     (mexp_macrostring 
	      (lambda (comp loc)
		(debug "expand_macrostring_pairs/mexp_macrostring comp=" comp "\n loc=" loc)
		(cond
		 ( (is_string comp)
		   (list_append chklist (make_string discr_verbatim_string comp)))
		 ( (is_a comp class_sexpr_macrostring)
		   (let ( 
			 (cloc (get_field :loca_location comp))
			 (compcont (get_field :sexp_contents comp))
			 )
		     (debug "expand_macrostring_pairs/mexp_macrostring compcont=" compcont)
		     (foreach_pair_component_in_list
		      (compcont)
		      (compair subcomp)
		      (mexp_macrostring subcomp cloc))
		     (debug "expand_macrostring_pairs/mexp_macrostring updated chklist=" chklist)
		     ))
		 ( (is_a comp class_sexpr)
		   (let ( (mcomp (mexpander comp env mexpander modctx))
			  )
		     (debug "expand_macrostring_pairs//mexp_macrostring mcomp=" mcomp)
		     (list_append chklist mcomp)))
		 (:else
		  (list_append chklist comp)))
		(debug "expand_macrostring_pairs/mexp_macrostring comp=" comp
		       "\n updated chklist=" chklist)))
	     )
      (foreach_pair
       (pairs)
       (thispair thiscomp)
       (debug "expand_macrostring_pairs thiscomp=" thiscomp)
       (mexp_macrostring thiscomp sloc)
       )
      (debug "expand_macrostring_pairs final chklist=" chklist)
      (let ( (tup (list_to_multiple chklist discr_multiple))
	     )
	(debug "expand_macrostring_pairs return tup=" tup)
	(return tup)
	))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; the code_chunk expander
(defun mexpand_code_chunk (sexpr env mexpander modctx)
  (debug "mexpand_code_chunk sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (sloc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (curchk ())
	 (gsym ())
	 (curel ())
	 )
    (setq curel (pair_head curpair))
    (if (is_a curel class_symbol)
	(setq gsym curel)
      (error_plain sloc "missing symbol in (CODE_CHUNK <state-symbol> <chunk>...)"))
    (setq curpair (pair_tail curpair))
    (let (
	  (tup (expand_macrostring_pairs curpair sloc env mexpander modctx))
	  (mres (instance class_source_codechunk
			  :loca_location sloc
			  :sch_gensym gsym
			  :sch_chunks tup
			  )) 
	  )
      (debug "mexpand_code_chunk return mres=" mres)
      (return mres)
      )))
(install_initial_macro 'code_chunk mexpand_code_chunk)
(export_macro code_chunk mexpand_code_chunk
	      :doc #{The $CODE_CHUNK macro is for low-level C code
chunks. The syntax is ($CODE_CHUNK @var{state-symbol} @var{chunk}...)
where @var{chunk}-s may be macro-strings or nested s-expressions. It
generates a C block. Nested expressions should be :void and are
expanded at place of occurence, as blocks. Since it does not make any
type verification, it should be used with parcimony. See $DEFPRIMITIVE
and $EXPR_CHUNK etc.}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; the expr_chunk expander
(defun mexpand_expr_chunk (sexpr env mexpander modctx)
  (debug "mexpand_expr_chunk sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (sloc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (curchk ())
	 (gsym ())
	 (kcty ())
	 (curel ())
	 )
    (setq curel (pair_head curpair))
    (if (is_a curel class_symbol)
	(setq gsym curel)
      (error_plain sloc "missing symbol in (EXPR_CHUNK <state-symbol> <ctype> <chunk>...)"))
    (setq curpair (pair_tail curpair))
    (setq kcty (pair_head curpair))
    (when (is_not_a kcty class_keyword)
      (error_plain sloc "missing type keyword in (EXPR_CHUNK <state-symbol> <ctype> <chunk>...)")
      (return))
    (setq curpair (pair_tail curpair))
    (let ( (cty (unsafe_get_field :symb_data kcty)) 
	   (typknam (unsafe_get_field :named_name kcty))
	   )
      (when (is_not_a cty class_ctype)
	(debug "mexpand_expr_chunk bad kcty=" kcty)
	(error_at sloc "bad type keyword for EXPR_CHUNK"_  typknam)
	(return ())
	)
      (cond ( (== (unsafe_get_field :ctype_keyword cty) kcty)
	      ()
	      )
	    ( (== (unsafe_get_field :ctype_altkeyword cty) kcty)
	      (warning_at sloc "using obsolete ctype keyword $1 in EXPR_CHUNK, preferring $2" 
			    typknam (get_field :named_name (get_field :ctype_keyword cty)))
	      )
	    (:else
	     (debug "mexpand_expr_chunk strange kcty=" kcty)
	     (error_at sloc "invalid type keyword $1 for EXPR_CHUNK"_
			 typknam)
	     (return ())   
	     ))
      (let (
	    (tup (expand_macrostring_pairs curpair sloc env mexpander modctx))
	    (mres (instance class_source_exprchunk
			    :loca_location sloc
			    :sch_gensym gsym
			    :sch_chunks tup
			    :sxch_ctype cty
			    )) 
	    )
	(debug "mexpand_expr_chunk return mres=" mres)
	(return mres)
	))))
(install_initial_macro 'expr_chunk mexpand_expr_chunk)
(export_macro expr_chunk mexpand_expr_chunk
	      :doc #{The $EXPR_CHUNK macro is for low-level C
@b{expression} chunks, e.g. anonymous primitive-like expressions. The
syntax is ($EXPR_CHUNK @var{state-symbol} @var{ctype} @var{chunk}...)  where
@var{chunk}-s may be macro-strings or sub-expressions. It generates a
C expressions, with all the sub-expressions strictly normalized before
the expansion of the @code{expr_chunk}. Since it does not make any
type verification, it should be usually avoided. See $DEFPRIMITIVE and
$EXPR_CHUNK etc.}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;; the unsafe_put_fields expander
(defun mexpand_unsafe_put_fields (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (fields ())
	 (fieldnams ())
	 (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (objsrc (pair_head curpair))
	 (objexp 
	  (if (is_a objsrc class_sexpr)
	      (mexpander objsrc env mexpander modctx)
	    objsrc))
	 )
    (setq curpair (pair_tail curpair))
    (let ( (fldlist (make_list discr_list))
	   )
      (forever insloop
	       (if (not (is_pair curpair)) (exit insloop))
	       (let ( (curfkw (pair_head curpair)) )
		 (if (is_not_a curfkw class_keyword)
		     (error_plain loc "expecting heyword in UNSAFE_PUT_FIELDS"_))
		 (setq curpair (pair_tail curpair))
		 (let ( (curexp (pair_head curpair)) )
		   (let  ( (flda (parse_field_assignment () loc curfkw curexp env mexpander modctx)) )
		     (if flda 
			 (list_append fldlist flda)
		       ))))
	       (setq curpair (pair_tail curpair))
	       )
      (let ( ( fastup (list_to_multiple fldlist discr_multiple)) )
	(instance class_source_unsafe_put_fields
		  :loca_location loc
		  :suput_obj objexp
		  :suput_fields fastup)
	))))
(install_initial_macro 'unsafe_put_fields mexpand_unsafe_put_fields)
(export_macro
 unsafe_put_fields mexpand_unsafe_put_fields
:doc #{The $UNSAFE_PUT_FIELDS is for expert use only, since it can
crash the running GCC MELT compilation. Syntax is (UNSAFE_PUT_FIELDS
<instance> @{:<field> <expression>@}). It sets fields in an instance
without any checks. Using $PUT_FIELDS is prefered.}#)

;;;; the put_fields expander
(defun mexpand_put_fields (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (let ( (fields ())
	 (fieldnams ())
	 (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (objsrc (pair_head curpair))
	 (objexp 
	  (if (is_a objsrc class_sexpr)
	      (mexpander objsrc env mexpander modctx)
	    objsrc))
	 )
    (setq curpair (pair_tail curpair))
    (let ( (fldlist (make_list discr_list))
	   )
      (forever insloop
	       (if (not (is_pair curpair)) (exit insloop))
	       (let ( (curfkw (pair_head curpair)) )
		 (if (is_not_a curfkw class_keyword)
		     (error_plain loc "expecting heyword in PUT_FIELDS"_))
		 (setq curpair (pair_tail curpair))
		 (let ( (curexp (pair_head curpair)) )
		   (let  ( (flda 
			    (parse_field_assignment () loc curfkw curexp env mexpander modctx)) )
		     (if flda 
			 (list_append fldlist flda)
		       ))))
	       (setq curpair (pair_tail curpair))
	       )
      (let ( ( fastup (list_to_multiple fldlist discr_multiple)) )
	(instance class_source_put_fields
		  :loca_location loc
		  :suput_obj objexp
		  :suput_fields fastup)
	))))
(install_initial_macro 'put_fields mexpand_put_fields)
(export_macro put_fields mexpand_put_fields
 :doc #{The $PUT_FIELDS syntax is for safely setting fields in an
 object. Syntax is (PUT_FIELDS <instance-expression> @{:<field>
 <field-expression>@}*). If the instance is not an object of the class
 containing all the fields, no harm is done. See also
 $UNSAFE_PUT_FIELDS which does not produces checks.}# )

;;;; the UNSAFE_GET_FIELD macro expander
(defun mexpand_unsafe_get_field (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (curfkw (pair_head curpair)) 
	 )
    (if (is_not_a curfkw class_keyword)
	(progn
	  (error_plain loc "field keyword expected in UNSAFE_GET_FIELD"_)
	  (return ())))
    (setq curpair (pair_tail curpair))
    (let ( (curexp (pair_head curpair)) )
      (setq curpair (pair_tail curpair))
      (if curpair (error_plain loc "UNSAFE_GET_FIELD with more than two sons"_))
      ;; it is not a field assignment but we use the parse_field_assignment
      ;; routine to get the field and the expression
      (let  ( (flda (parse_field_assignment () loc curfkw curexp env mexpander modctx)) )
	(if (not (is_a flda class_source_fieldassign))
	    (progn 
	      (error_plain loc "bad field and expression in UNSAFE_GET_FIELD"_)
	      (return ())))
	(let ( (fld (unsafe_get_field :sfla_field flda))
	       (exp (unsafe_get_field :sfla_expr flda)) )
	  (if (null exp)
	      (error_plain loc "missing object expression for (UNSAFE_GET_FIELD :field objexpr)"))
	  (instance class_source_unsafe_get_field
		    :loca_location loc
		    :suget_obj exp
		    :suget_field fld
		    ))))))
(install_initial_macro 'unsafe_get_field mexpand_unsafe_get_field)
(export_macro
 unsafe_get_field mexpand_unsafe_get_field
 :doc #{The $UNSAFE_GET_FIELD syntax retrieves dangerously a field
 from an instance and may crash when the instance is not an object of
 the appropriate class. Syntax is (UNSAFE_GET_FIELD :<field>
 <expression>). Using $GET_FIELD is preferrable.}#)

;;;; the GET_FIELD expander
(defun mexpand_get_field (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (curfkw (pair_head curpair)) 
	 )
    (if (is_not_a curfkw class_keyword)
	(progn
	  (error_plain loc "field keyword expected in GET_FIELD"_)
	  (return ())))
    (setq curpair (pair_tail curpair))
    (let ( (curexp (pair_head curpair)) )
      (setq curpair (pair_tail curpair))
      (if curpair (error_plain loc "UNSAFE_GET_FIELD with more than two sons"_))
      ;; it is not a field assignment but we use the parse_field_assignment
      ;; routine to get the field and the expression
      (let  ( (flda (parse_field_assignment () loc curfkw curexp env mexpander modctx)) )
	(if (not (is_a flda class_source_fieldassign))
	    (progn 
	      (error_plain loc "bad field and expression in GET_FIELD"_)
	      (return ())))
	(let ( (fld (unsafe_get_field :sfla_field flda))
	       (exp (unsafe_get_field :sfla_expr flda)) )
	  (if (null exp)
	      (error_plain loc "missing object expression for (GET_FIELD :field objexpr)"))
	  (instance class_source_get_field
		    :loca_location loc
		    :suget_obj exp
		    :suget_field fld
		    ))))))
(install_initial_macro 'get_field mexpand_get_field)
(export_macro get_field mexpand_get_field
 :doc #{The $GET_FIELD syntax safely access a field. Syntax
 is (GET_FIELD :<field> <expression>) which evaluates to nil if the
 expression is not of the class defining the field. See also
 $UNSAFE_GET_FIELD.}#)


;; internal routine to make a progn from a pairlist at a location
(defun pairlist_to_progn (pair loc env mexpander modctx)
  (debug "pairlist_to_progn pair=" pair)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check_pair" (is_pair pair) pair)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (bodytup (expand_pairlist_as_tuple pair env mexpander modctx))
	 (sprogn
	  (instance class_source_progn
		    :loca_location loc
		    :sprogn_body bodytup
		    )) )
    (debug "pairlist_to_progn sprogn" sprogn)
    (return sprogn)
    ))

;;;; the setq expander
(defun mexpand_setq (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont)))
	 (cursym (pair_head curpair)) 
	 )
    (if (is_not_a cursym class_symbol)
	(progn
	  (error_plain loc "var symbol name expected in SETQ"_)
	  (return ())))
    (setq curpair (pair_tail curpair))
    (let ( (curexp (pair_head curpair)) )
      (setq curpair (pair_tail curpair))
      (if curpair (error_plain loc "SETQ with more than two sons"_))
      (instance class_source_setq 
		:loca_location loc
		:sstq_var cursym
		:sstq_expr  (mexpander curexp env mexpander modctx)
		)
      )))
(install_initial_macro 'setq mexpand_setq)
(export_macro setq mexpand_setq
 :doc #{The $SETQ syntax is for assignment of local variables, usually
 bound by a LET in the same function. Syntax is (SETQ <symbol>
 <expr>).}#)

;;;;; the if expanser
(defun mexpand_if (sexpr env mexpander modctx)
  (debug "mexpand_if sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(curif (pair_head curpair)) )
    (if (not (is_pair curpair))
	(error_plain loc "missing condition in IF"_))
    (setq curpair (pair_tail curpair))
    (if (not (is_pair curpair))
	(error_plain loc "missing then in IF"_))
    (let ( (xcond (mexpander curif env mexpander modctx)) )
      (debug "mexpand_if xcond" xcond)
      (let ( (curthen (pair_head curpair)) )
	(setq curpair (pair_tail curpair))
	(let ( (xthen (mexpander curthen env mexpander modctx)) 
	       )
	  (debug "mexpand_if xthen" xthen)
	  (if (is_pair curpair)
	      (let ( (curelse (pair_head curpair)) 
		     (xelse (mexpander curelse env mexpander modctx)) )
		(debug "mexpand_if xelse" xelse)
		(setq curpair (pair_tail curpair))
		(if (is_pair curpair)
		    (error_plain loc "IF with more than three sons"_))
		(let ( (rese
			(instance class_source_ifelse
				  :loca_location loc
				  :sif_test xcond
				  :sif_then xthen
				  :sif_else xelse
				  )) )
		  (debug "mexpand_if with else return rese" rese)
		  (return rese)))
	    (let ( (resp (instance class_source_if
				   :loca_location loc
				   :sif_test xcond
				   :sif_then xthen)) )
	      (debug "mexpand_if plain return resp" resp)
	      (return resp))
	    ))))))
(install_initial_macro 'if mexpand_if)
(export_macro if mexpand_if
 :doc #{The $IF syntax is for simple conditional expressions. See also $WHEN and $UNLESS and $COND. Syntax
 is (IF <test-expression> <then-expression> [<else-expression>]).}#)


;;;;;;;;;;;;;;;;
;;;; WHEN macro = syntactic sugar (WHEN <test> <body...>) === (IF <test> (PROGN <body...>))
(defun mexpand_when (sexpr env mexpander modctx)
  (debug "mexpand_when sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(curif (pair_head curpair)) 
	)
    (if (not (is_pair curpair))
	(error_plain loc "missing condition in WHEN"_))
    (setq curpair (pair_tail curpair))
    (if (not (is_pair curpair))
	(error_plain loc "missing body in WHEN"_))
    (let ( (xcond (mexpander curif env mexpander modctx))
	   (xprogn (pairlist_to_progn curpair loc env mexpander modctx))
	   (xwhen (instance class_source_if
			    :loca_location loc
			    :sif_test xcond
			    :sif_then xprogn))
	   )
      (debug "mexpand_when return xwhen=" xwhen)
      (return xwhen)
      )))

(install_initial_macro 'when mexpand_when)
(export_macro  when mexpand_when
 :doc #{The $WHEN syntax sugar is for conditional expressions with body. Syntax
 is (WHEN <test> <body>...) syntactic sugar for (IF <test> (PROGN <body>...)).}#)


;;;;;;;;;;;;;;;;
;;;; UNLESS macro = syntactic sugar (UNLESS <test> <body...>) === (IF <test> () (PROGN <body...>))
(defun mexpand_unless (sexpr env mexpander modctx)
  (debug "mexpand_unless sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(curif (pair_head curpair)) 
	)
    (if (not (is_pair curpair))
	(error_plain loc "missing condition in UNLESS"_))
    (setq curpair (pair_tail curpair))
    (if (not (is_pair curpair))
	(error_plain loc "missing body in UNLESS"_))
    (let ( (xcond (mexpander curif env mexpander modctx))
	   (xprogn (pairlist_to_progn curpair loc env mexpander modctx))
	   (xunless (instance class_source_ifelse
			    :loca_location loc
			    :sif_test xcond
			    :sif_then ()
			    :sif_else xprogn))
	   )
      (debug "mexpand_unless return xunless=" xunless)
      (return xunless)
      )))

(install_initial_macro 'unless mexpand_unless)
(export_macro  unless mexpand_unless
 :doc #{The $UNLESS syntax sugar is for negated conditional expressions with body. Syntax
 is @code{(UNLESS @var{<test>} @var{<body>...})} = syntactic sugar for @code{(IF @var{<test>} () (PROGN @var{<body>...}))}.}#)


;;;;;;;;;;;;;;;;
;;;; WITH_CLONED_SYMB macro = 
;;; syntactic sugar (WITH_CLONED_SYMB (<symb1>...) <body...>) 
;;;     == (LET ((<symb1> (CLONE_SYMBOL <symb1>)) ....) <body...>)
(defun mexpand_with_cloned_symb (sexpr env mexpander modctx)
  (debug "mexpand_with_cloned_symb sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(symbs (pair_head curpair))
	(newenv (fresh_env env))
	(bindlist (make_list discr_list))
	(bodyl ())
	(processlist 
	 (lambda (bloc blist)
	   (debug "mexpand_with_cloned_symb/processlist bloc=" bloc " blist=" blist)
	   (assert_msg "check blist" (is_list_or_null blist) blist)
	   (foreach_pair_component_in_list
	    (blist)
	    (curpair cursymb)
	    (when (is_not_a cursymb class_symbol)
	      (error_plain bloc "non-symbol in symbol list for (WITH_CLONED_SYMB <symbol-list> <body...>)")
	      (return))
	    (if (is_a cursymb class_keyword)
		(warning_strv bloc "keyword in WITH_CLONED_SYMB is discouraged"
			      (get_field :named_name cursymb)))
	    (if (find_env newenv cursymb)
		(warning_strv bloc "symbol in WITH_CLONED_SYMB hides previous definition"
			      (get_field :named_name cursymb)))
	    (let ( (appclonesymb (instance class_source_apply 
					   :loca_location bloc
					   :sapp_fun 'clone_symbol
					   :sargop_args (tuple (instance class_source_quote
									 :loca_location bloc
									 :squoted cursymb))))
		   ;; notice that class_source_let_binding is not a binding, but an AST construct...
		   (bindsymb (instance class_source_let_binding
				       :loca_location bloc
				       :sletb_type ctype_value
				       :sletb_binder cursymb
				       :sletb_expr appclonesymb
				       ))
		   ;; this is the binding to extend the environment...
		   (bind (instance class_let_binding
				   :binder cursymb
				   :letbind_type ctype_value
				   :letbind_expr appclonesymb
				   :letbind_loc bloc))
		   )
	      (put_env newenv bind)
	      (list_append bindlist bindsymb)
	      (debug "mexpand_with_cloned_symb/processlist end bindsymb=" bindsymb)
	      )
	    )))
	)
    (setq curpair (pair_tail curpair))
    ;; parse the symbol list and build bindlist
    (debug "mexpand_with_cloned_symb symbs=" symbs)
    (cond ( (null symbs)
	    (void)
	    )
	  ( (is_a symbs class_sexpr)
	    (let ( (syloc (or (unsafe_get_field :loca_location symbs) loc))
		   (sylist (unsafe_get_field :sexp_contents symbs))
		   )
	      (processlist syloc sylist)
	      (void)
	      ))
	  ( (is_list symbs)
	    (processlist loc symbs)
	    (void))
	  ( (is_multiple symbs)
	    (processlist loc (multiple_to_list symbs discr_list))
	    (void))
	  (:else
	   (error_plain loc "WITH_CLONED_SYMB wants a list of symbols as first argument")
	   (return () ())))
    (debug "mexpand_with_cloned_symb bindlist=" bindlist)
    ;; expand the body
    (let ( (mbody (expand_pairlist_as_tuple curpair newenv mexpander modctx))
	   (mlet (instance class_source_let
			   :loca_location loc
			   :slet_bindings (list_to_multiple bindlist discr_multiple)
			   :slet_body mbody
			   ))
	   )
      (debug "mexpand_with_cloned_symb mbody=" mbody "\n.. result mlet=" mlet)
      (return mlet)
      )))
(install_initial_macro 'with_cloned_symb mexpand_with_cloned_symb)
(export_macro with_cloned_symb mexpand_with_cloned_symb
 :doc #{The $WITH_CLONED_SYMB syntax sugar is for easily cloning symbols, notably useful in macros. 
Syntax is @code{(WITH_CLONED_SYMB (@var{<symb>...}) @var{<body>...})} same as
@code{(LET ( (@var{<symb>} (CLONE_SYMBOL (QUOTE @var{<symb>}))) @var{...})  @var{<body>...})} etc...}#)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;
;;;;; the CPPIF expander
(defun mexpand_cppif (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (debug "mexpand_cppif sexpr" sexpr)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(curif (pair_head curpair)) 
	)
    (if (not (is_pair curpair))
	(error_plain loc "missing condition in CPPIF"_))
    (setq curpair (pair_tail curpair))
    (if (not (is_pair curpair))
	(error_plain loc "missing then in CPPIF"_))
    (let ( (xcond (mexpander curif env mexpander modctx)) )
      (debug "mexpand_cppif xcond" xcond)
      (cond 
       ( (is_string xcond) ())
       ( (is_a xcond class_symbol) ())
       (:else
	(error_plain loc "invalid cpp-condition in CPPIF - string or symbol expected"_)
	(return ())))
      (let ( (curthen (pair_head curpair)) )
	(setq curpair (pair_tail curpair))
	(let ( (xthen (mexpander curthen env mexpander modctx)) 
	       (xelse ())
	       )
	  (debug "mexpand_cppif xthen" xthen)
	  (if (is_pair curpair)
	      (let ( (curelse (pair_head curpair)) 
		     (gotxelse (mexpander curelse env mexpander modctx)) )
		(debug "mexpand_cppif gotxelse" gotxelse)
		(setq curpair (pair_tail curpair))
		(setq xelse gotxelse)
		(if (is_pair curpair)
		    (error_plain loc "CPPIF with more than three sons"_))))
	  (let ( (resp (instance class_source_cppif
				 :loca_location loc
				 :sifp_cond xcond
				 :sifp_then xthen
				 :sifp_else xelse
				 ))
		 )
	    (debug "mexpand_cppif return resp" resp)
	    (return resp)
	    ))))))
(install_initial_macro 'cppif mexpand_cppif)
(export_macro cppif mexpand_cppif
 :doc #{The $CPPIF macro expands to C-code with an #if condition, so
the condition is handled when compiling the generated C code into a
MELT module.  Syntax is (CPPIF <symbol> <then> [<else>]).}#)

;;;;; the cond expanser
(defun mexpand_cond (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (debug "mexpand_cond sexpr" sexpr)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(cexptuple (pairlist_to_multiple 
		    (pair_tail (list_first cont))
		    discr_multiple
		    (lambda (c)
		      (if (is_not_a c class_sexpr)
			  (error_plain loc "COND with non-sexpr"_))
		      c
		      ))) 
	(:long nbcond (multiple_length cexptuple))
	(lastcexp (let ( (lx (multiple_nth cexptuple -1)) )
		    (debug "mexpand_cond lastcexp lx" lx)
		    lx))
	(:long ix (-i nbcond 1))
	(res ())
	)
    (debug "mexpand_cond cexptuple" cexptuple)
    (forever condloop
	     (if (<i ix 0) (exit condloop))
	     (let ( (curcond (multiple_nth cexptuple ix)) )
	       (debug "mexpand_cond curcond" curcond)
	       (cond  
		( (and (null res)
		       (is_a curcond class_sexpr)
		       (== ':else (pair_head (list_first 
					      (unsafe_get_field :sexp_contents curcond)))))
		  (let ( (restpairs 
			  (pair_tail (list_first (unsafe_get_field :sexp_contents curcond)))) 
			 )
		    (if restpairs 
			(setq res (pairlist_to_progn restpairs 
						     (unsafe_get_field :loca_location curcond) 
						     env mexpander
						     modctx)))
		    (debug "mexpand_cond res for :else" res)
		    ))
		( (is_a curcond class_sexpr)
		  (let ( (curcondcont (unsafe_get_field :sexp_contents curcond))
			 (curcondloc (unsafe_get_field :loca_location curcond)) 
			 (curcondtest (pair_head (list_first curcondcont)))
			 (curcondrestpairs (pair_tail (list_first curcondcont))) 
			 )
		    (cond ( (null curcondrestpairs)
			    (setq res 
				  (instance class_source_or
					    :loca_location curcondloc
					    :sor_disj
					    (tuple
					     (mexpander curcondtest env mexpander modctx)
					     res)))
			    (debug "mexpand_cond res for monoexp cond" res)
			    )
			  ( (null (pair_tail curcondrestpairs))
			    (setq res
				  (instance class_source_ifelse
					    :loca_location curcondloc
					    :sif_test (mexpander curcondtest env mexpander modctx)
					    :sif_then (mexpander (pair_head curcondrestpairs) env mexpander modctx)
					    :sif_else res
						))
			    (debug "mexpand_cond res for biexp cond" res)
			    )
			  (:else 
			   (setq res
				 (instance class_source_ifelse
					   :loca_location curcondloc
					   :sif_test (mexpander curcondtest env mexpander modctx)
					   :sif_then (pairlist_to_progn curcondrestpairs curcondloc env mexpander modctx)
					       :sif_else res))
			   (debug "mexpand_cond res for manyexp cond" res)
			   ))
		    ))
		(:else ;curcond is not a sexpr 
		 (setq res (instance class_source_or
				     :loca_location loc
				     :sor_disj (tuple curcond res)))
		 (debug "mexpand_cond res for nonsexp cond" res)
		 )
		)
	       )
	     (setq ix (-i ix 1))
	     )
    (debug "mexpand_cond final res" res)
    (return res)
    ))
(install_initial_macro 'cond mexpand_cond)
(export_macro cond mexpand_cond
 :doc #{The usual lisp $COND conditional. Syntax is @code{(COND
 @var{<conditions>...})}. Each condition is a list of the form
 @code{(@var{<test>} @var{<expr>...})}. The last catch-all condition
 can be @code{(:else @var{<epxr>...})}.}#)


;;;;;;;;;;;;;;;;
;;;; the AND macro expanser
;;; AND pseudo syntax
;;; (AND a1) is expanded into a1
;;; (AND a1 a2) is expansed into (IF a1 a2)
;;; (AND a1 a2 a3) is expansed into (IF a1 (IF a2 a3))
(defun mexpand_and (sexpr env mexpander modctx)
  (debug  "mexpand_and sexpr:" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(cxtup (expand_pairlist_as_tuple curpair env mexpander modctx))
	(:long nbcomp (multiple_length cxtup))
	)
    (debug "mexpand_and cxtup" cxtup)
    (if (<i nbcomp 1)
	(progn
	  (error_plain loc "AND without sons"_)
	  (return))
      (let ( (res (multiple_nth cxtup (-i nbcomp 1)))
	     (:long ix (-i nbcomp 2)) )
	(forever revloop
		 (if (<i ix 0) (exit revloop))
		 (let ( (curc (multiple_nth cxtup ix)) )
		   (setq res 
			 (instance class_source_if
				   :loca_location loc
				   :sif_test curc
				   :sif_then res))
		   )
		 (setq ix (-i ix 1))
		 )
	(debug "mexpand_and res:" res)
	(return res)))))


;;;; the AS pattern expander
(defun patexpand_as (sexpr env pctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (debug "patexpand_as sexpr" sexpr)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(argsp (patternexpand_pairlist_as_tuple curpair env pctx loc))
	)
    (if (!=i (multiple_length argsp) 2)
	(progn
	  (error_plain loc "AS pattern expects two arguments: ?patvar subpattern")
	  (return)))
    (let ( (argvar (multiple_nth argsp 0))
	   (argsub (multiple_nth argsp 1))
	   )
      (if (is_a argvar class_source_pattern_joker_variable)
	  (progn
	    (warning_plain loc "AS pattern with useless joker")
	    (return argsub)))
      (if (is_not_a argvar class_source_pattern_variable)
	  (progn
	    (error_plain loc "AS pattern needs a pattern variable as first argument")
	    (return)))
      (warning_plain loc "deprecated AS pattern - use AND pattern instead")
      (let (
	    (:long subw (get_int (get_field :pat_weight argsub)))
	    (res (instance class_source_pattern_and
			   :loca_location loc
			   :pat_weight (make_integerbox discr_constant_integer (+i 2 subw))
			   :andpat_conj (tuple argvar argsub)))
	    )
	(debug "patexpand_as returns res" res)
	(return res)
	))))

(defun mexpand_as (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (debug "mexpand_as sexpr=" sexpr)
  (let (
	(loc  (unsafe_get_field :loca_location sexpr))
	)
    (error_plain loc "AS cannot be macro-expanded in expression context")
    (return)
))
(install_initial_patmacro 'as patexpand_as mexpand_as)
(export_patmacro as patexpand_as mexpand_as)

;;;; the WHEN pattern expanser
(defun patexpand_when (sexpr env pctx)
  (debug "patexpand_when sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	)
    (compile_warning "patexpand_when not implemented yet")
    (error_plain loc "WHEN is not yet implemented in patterns")
    (assert_msg "@$@ unimplemented patexpand_when" () sexpr)
    (return)
    ))

(install_initial_patmacro 'when patexpand_when mexpand_when)
(export_patmacro when patexpand_when mexpand_when)


;;;; the AND pattern expanser
(defun patexpand_and (sexpr env pctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (debug "patexpand_and sexpr" sexpr)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(argsp (patternexpand_pairlist_as_tuple curpair env pctx loc))
	(res (instance class_source_pattern_and
		       :loca_location loc
		       :andpat_conj argsp))
	)
    (multicall
     (subpatw :long imax imin isum)
     (pattern_weight_tuple argsp)
     (unsafe_put_fields res
			:pat_weight (make_integerbox discr_constant_integer
						     (+i (+i 1 imax) isum))))
    (debug "patexpand_and res" res)
    (return res)
    ))

(install_initial_patmacro 'and patexpand_and mexpand_and)
(export_patmacro and patexpand_and mexpand_and
 :doc #{The lispy $AND conjunction syntax is a short-circuit "and
 then" conjunction. Expression syntax is (AND
 <conjunct-subexpression>...) and can evaluate to a :value or a thing
 such as a :long or a :gimple which is null/zero iff any conjunct is
 null or zero. Pattern syntax is ?(AND <conjunct-subpattern>...) and
 matches if all conjunct-subpattern-s match. See also $COND $OR and
 $IF.}#)

;;;;;;;;;;;;;;;;
;;;; the OR macro expanser
(defun mexpand_or (sexpr env mexpander modctx)
  (debug "mexpand_or sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(cxtup (expand_pairlist_as_tuple (pair_tail (list_first cont)) env mexpander modctx))
	(:long nbcomp (multiple_length cxtup))
	)
    (if (<i nbcomp 1)
	(progn 
	  (error_plain loc "OR without sons"_)
	  (return ()))
      (let ( (res 
	      (instance class_source_or
			:loca_location loc
			:sor_disj cxtup)) )
	 (debug "mexpand_or res" res)
	 (return res)
	 ))))

;;;; the OR pattern expander
(defun patexpand_or (sexpr env pctx)
  (debug "patexpand_or sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(argsp (patternexpand_pairlist_as_tuple curpair env pctx loc))
	(res (instance class_source_pattern_or
		       :loca_location loc
		       :orpat_disj argsp))
	)
    (multicall
     (subpatw :long imax imin isum)
     (pattern_weight_tuple argsp)
     (unsafe_put_fields
      res 
      :pat_weight (make_integerbox discr_constant_integer (+i 1 imin)))
     (debug "patexpand_or res" res)
     (return res)
     )))
(install_initial_patmacro 'or patexpand_or mexpand_or)
(export_patmacro or patexpand_or mexpand_or
 :doc #{The lispy $OR disjunctive syntax is a short-circuit "or else"
 disjonction. Expression syntax is (OR <disjunct-subexpression>...)
 and can evaluate to a :value or a thing such as a :gimple or a :long
 etc. which is null/zero iff every disjunct is
 null/zero. Pattern-syntax is ?(OR <disjunct-subpattern>...) and
 matches if one of the disjunct-subpattern matches. See also $COND
 $AND and $IF.}# )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; CONTENT & REFERENCE

;; (reference x) is a shorthand for 
;; (instance class_reference :referenced_value x)
(defun mexpand_reference (sexpr env mexpander modctx)
  (debug "mexpand_reference sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (assert_msg "check class_reference has one field"
	      (==i 1 (multiple_length
		     (get_field :class_fields class_reference)))
	      class_fields
	      )
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(:long nbarg (multiple_length xargtup))
	(arg1 (multiple_nth xargtup 0))
	(spredclasscont (instance class_source_fetch_predefined
				  :loca_location loc
				  :sfepd_predef 'CLASS_REFERENCE))
	(clabind (find_env env 'class_reference))
	(flda (parse_field_assignment 
	       class_reference loc :referenced_value arg1 env mexpander modctx))
	(sinst (instance 
		class_source_instance
		:loca_location loc
		:smins_class class_reference
		:smins_clabind clabind
		:smins_fields (tuple flda)))
	)
    (if (!=i nbarg 1)
	(progn
	  (error_plain loc "(REFERENCE <value>) needs exactly one argument")
	  (return)))
    ;; testing that clabind binds exactly the same class_reference
    ;; don't work well for makedoc mode.
    (if (null clabind)
	(warning_plain loc  "(REFERENCE <value>) where CLASS_REFERENCE is not visible"))
    ;;
    (debug "mexpand_reference returns sinst" sinst)
    (return sinst)
))


(defun patexpand_reference (sexpr env pctx)
  (debug "patexpand_reference sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(argsp (patternexpand_pairlist_as_tuple curpair env pctx loc))
	(arg1 (multiple_nth argsp 0))
	(fldp (parse_field_pattern :referenced_value class_reference arg1 env pctx loc))
	(res (instance class_source_pattern_instance
		       :loca_location loc
		       :pat_weight '1
		       :spat_class class_reference
		       :spat_fields (tuple fldp)))
	)
    (if (!=i (multiple_length argsp) 1)
	(progn
	  (error_plain loc "(REFERENCE <subpattern>) pattern needs one argument")
	  (return)))
    (debug "patexpand_reference res" res)
    (return res)
))
(install_initial_patmacro 'reference patexpand_reference mexpand_reference)
(export_patmacro reference patexpand_reference mexpand_reference
 :doc #{The $REFERENCE syntax is a short-hand for making or matching
 instances of $CLASS_REFERENCE. Expression syntax (REFERENCE
 <subexpression>) is a short-hand for (INSTANCE
 CLASS_REFERENCE :REFERENCED_VALUE <subexpression>) to make an instance
 of $CLASS_REFERENCE with the given value as $REFERENCED_VALUE. Pattern
 syntax is ?(REFERENCE <subpattern>) to match an instance of
 $CLASS_REFERENCE with its $REFERENCED_VALUE matching
 <subpattern>. $REFERENCE expressions are constructive, so can appear
 in $LETREC bindings.}#)


;; (deref x) is a shorthand for 
;; (get_field :referenced_value x)
(defun mexpand_deref (sexpr env mexpander modctx)
  (debug "mexpand_deref sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (assert_msg "check class_reference has one field"
	      (==i 1 (multiple_length
		     (get_field :class_fields class_reference)))
	      class_reference)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(:long nbarg (multiple_length xargtup))
	(arg1 (multiple_nth xargtup 0))
	(spredclasscont (instance class_source_fetch_predefined
				  :loca_location loc
				  :sfepd_predef 'CLASS_REFERENCE))
	(clabind (find_env env 'class_reference))
	(sget (instance 
		class_source_get_field
		:loca_location loc
		:suget_obj arg1
		:suget_field referenced_value))
	)
    (assert_msg "check referenced_value" (is_a referenced_value class_field) referenced_value)
    (if (!=i nbarg 1)
	(progn
	  (error_plain loc "(DEREF <value>) needs exactly one argument")
	  (return)))
    ;; testing that clabind binds exactly the same class_reference
    ;; don't work well for makedoc mode.
    (if (null clabind)
	(warning_plain loc  "(DEREF <value>) where CLASS_REFERENCE is not visible"))
    (debug "mexpand_deref returns sget" sget)
    (return sget)))

(install_initial_macro 'deref mexpand_deref)
(export_macro deref mexpand_deref
 :doc #{The $DEREF macro is a short-hand to retrieve values inside
 instances of $CLASS_REFERENCE. So @code{(DEREF @var{<value>})}
 means @code{(GET_FIELD :REFERENCED_VALUE @var{<value>})}, hence test that @var{<value>}
 is indeed an instance of $CLASS_REFERENCE, or else gives null. The special syntax @code{!@var{<expr>}} is a syntactic sugar for @code{(DEREF @var{<expr>})}.}#)


(defun mexpandobsolete_content (sexpr env mexpander modctx)
  (debug "mexpandobsolete_content sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (warning_plain (get_field :loca_location sexpr)
		 "obsolete use of CONTENT in expression; use DEREF instead")
  (mexpand_deref sexpr env mexpander modctx))
(install_initial_macro 'content mexpandobsolete_content)
(export_macro content mexpandobsolete_content
 :doc #{The $CONTENT macro is obsolete. Use $DEREF instead.}#)


;;; exclaim is the same as deref, but export_synonym don't work for macros
(install_initial_macro 'exclaim mexpand_deref)
(export_macro exclaim mexpand_deref 
 :doc #{$EXCLAIM [usually given thru the ! syntactic sugar] is a
 synonym for $DEREF, e.g. @code{!(IF p c)} means @code{(DEREF (IF P C))}
 hence @code{(GET_FIELD :REFERENCED_VALUE (IF P C))}}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; SET_REF

;; (set_ref r x) is a shorthand for 
;; (put_fields r :referenced_value x)
(defun mexpand_set_ref (sexpr env mexpander modctx)
  (debug "mexpand_set_ref sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (assert_msg "check class_reference has one field"
	      (==i 1 (multiple_length
		     (get_field :class_fields class_reference)))
	      class_reference)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(:long nbarg (multiple_length xargtup))
	(arg1 (multiple_nth xargtup 0))
	(arg2 (multiple_nth xargtup 1))
	(spredclasscont (instance class_source_fetch_predefined
				  :loca_location loc
				  :sfepd_predef 'CLASS_REFERENCE))
	(clabind (find_env env 'class_reference))
	(putup (tuple (instance class_source_fieldassign 
			 :loca_location loc
			 :sfla_field referenced_value
			 :sfla_expr arg2
			 )
		))
	(sput (instance 
		class_source_put_fields
		:loca_location loc
		:suput_obj arg1
		:suput_fields putup))
	)
    (assert_msg "check referenced_value" (is_a referenced_value class_field) referenced_value)
    (if (!=i nbarg 2)
	(progn
	  (error_plain loc "(SET_REF <ref> <value>) needs exactly two arguments")
	  (return)))
    ;; testing that clabind binds exactly the same class_reference
    ;; don't work well for makedoc mode.
    (if (null clabind)
	(warning_plain loc  "(SET_REF <ref> <value>) where CLASS_REFERENCE is not visible"))
    (debug "mexpand_set_ref returns sput" sput)
    (return sput)))

(install_initial_macro 'set_ref mexpand_set_ref)
(export_macro set_ref mexpand_set_ref
 :doc #{The $SET_REF macro is a short-hand to put a value inside
 instances of $CLASS_REFERENCE. So @code{(SET_REF @var{<ref>} @var{<value>})}
 means @code{(PUT_FIELDS @var{<ref>} :REFERENCED_VALUE @var{<value>})}, hence test that @var{<ref>}
 is indeed an instance of $CLASS_REFERENCE before updating it.}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + 
;;;; the + macro expander
(defun mexpand_plus  (sexpr env mexpander modctx)
  (debug "mexpand_plus sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(res (instance class_source_arithmetic_variadic_operation
	      :loca_location loc
	      :sargop_args xargtup
	      :sarithvar_neutral '0
	      :sarithvar_primitive +i
	      ))
	)
    (when (==i 0 (multiple_length xargtup))
      (error_plain loc "+ operator needs at least one argument")
      (return))
    (debug "mexpand_plus result" res)
    (return res)
    ))
(install_initial_macro '+ mexpand_plus)
(export_macro + mexpand_plus
 :doc #{The addition @code{+} operator is variadic, and understood as successive 
applications of @code{+i} primitives.}#
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - 
;;;; the - macro expander
(defun mexpand_minus  (sexpr env mexpander modctx)
  (debug "mexpand_minus sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(res (instance class_source_arithmetic_variadic_operation
	      :loca_location loc
	      :sargop_args xargtup
	      :sarithvar_neutral '0
	      :sarithvar_primitive -i
	      ))
	)
    (when (==i 0 (multiple_length xargtup))
      (error_plain loc "- operator needs at least one argument")
      (return))
    (debug "mexpand_minus result" res)
    (return res)
    ))
(install_initial_macro '- mexpand_minus)
(export_macro - mexpand_minus
 :doc #{The substraction @code{-} operator is variadic, and understood as successive 
applications of @code{-i} primitives.}#
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - 
;;;; the * macro expander
(defun mexpand_times  (sexpr env mexpander modctx)
  (debug "mexpand_times sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(res (instance class_source_arithmetic_variadic_operation
	      :loca_location loc
	      :sargop_args xargtup
	      :sarithvar_neutral '1
	      :sarithvar_primitive *i
	      ))
	)
    (when (==i 0 (multiple_length xargtup))
      (error_plain loc "* operator needs at least one argument")
      (return))
    (debug "mexpand_times result" res)
    (return res)
    ))
(install_initial_macro '* mexpand_times)
(export_macro * mexpand_times
 :doc #{The product @code{*} operator is variadic, and understood as successive 
applications of @code{*i} primitives.}#
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; - 
;;;; the / macro expander
(defun mexpand_div  (sexpr env mexpander modctx)
  (debug "mexpand_div sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(res (instance class_source_arithmetic_variadic_operation
	      :loca_location loc
	      :sargop_args xargtup
	      :sarithvar_neutral '1
	      :sarithvar_primitive /i
	      ))
	)
    (when (==i 0 (multiple_length xargtup))
      (error_plain loc "/ operator needs at least one argument")
      (return))
    (debug "mexpand_div result" res)
    (return res)
    ))
(install_initial_macro '/ mexpand_div)
(export_macro / mexpand_div
 :doc #{The division @code{/} operator is variadic, and understood as successive 
applications of @code{/i} primitives.}#
)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; TUPLE 
;;;; the TUPLE macro expander
(defun mexpand_tuple  (sexpr env mexpander modctx)
  (debug "mexpand_tuple sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(res (instance class_source_tuple
	      :loca_location loc
	      :sargop_args xargtup))
	)
    (debug "mexpand_tuple result" res)
    (return res)
    ))

;;;; the TUPLE pattern expander
(defun patexpand_tuple (sexpr env pctx)
  (debug "patexpand_tuple sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(argsp (patternexpand_pairlist_as_tuple curpair env pctx loc))
	(res (instance class_source_pattern_tuple
		       :loca_location loc
		       :ctpat_subpa argsp))
	)
    (debug "patexpand_tuple res" res)
    (return res)
))
(install_initial_patmacro 'tuple patexpand_tuple mexpand_tuple)
(export_patmacro tuple patexpand_tuple mexpand_tuple
 :doc #{The $TUPLE syntax is for making or matching tuples. Expression
 syntax is (TUPLE <component-subexpression>...) to make a tuple of
 $DISCR_MULTIPLE with the given components. Pattern syntax is ?(TUPLE
 <component-subpattern>...) to match a tuple of given length with each
 component matching its corresponding <component-subpattern>. $TUPLE
 expressions are constructive, so can appear in $LETREC
 bindings.}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LIST 
;;;; the LIST macro expander
(defun mexpand_list  (sexpr env mexpander modctx)
  (debug "mexpand_list sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	(res  (instance class_source_list
	      :loca_location loc
	      :sargop_args xargtup))
	)
    (debug "mexpand_list result" res)
    (return res)
    ))

;;;; the LIST pattern expander
(defun patexpand_list (sexpr env pctx)
  (debug "patexpand_list sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check pctx" (is_a pctx class_pattern_expansion_context) pctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(argsp (patternexpand_pairlist_as_tuple curpair env pctx loc))
	(res (instance class_source_pattern_list
		       :loca_location loc
		       :ctpat_subpa argsp))
	)
    (debug "patexpand_list res" res)
    (return res)
))
(install_initial_patmacro 'list patexpand_list mexpand_list)
(export_patmacro list patexpand_list mexpand_list
 :doc #{The $LIST syntax is for making or matching lists made of
 pairs. Expression syntax is (LIST <component-subexpression>...) to
 make a list of $DISCR_LIST with the given components going into the
 head of pairs of $DISCR_PAIR. Pattern syntax is ?(LIST
 <component-subpattern>...) to match a list of given length with each
 component matching its corresponding <component-subpattern>. $LIST
 expressions are constructive, so can appear in $LETREC bindings.}#)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; the match expander
(defun mexpand_match (sexpr env mexpander modctx)
  (debug "mexpand_match sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(msexp (pair_head (pair_tail (list_first cont))))
	(matsx (mexpander msexp env mexpander modctx))
	(mexptuple (pairlist_to_multiple 
		    (pair_tail (pair_tail (list_first cont)))
		    discr_multiple
		    (lambda (c)
		      (if (is_not_a c class_sexpr)
			  (error_plain loc "MATCH with non-sexpr"_))
		      c
		      ))) 
	(:long nbmatch (multiple_length mexptuple))
	(lastmexp (let ( (lx (multiple_nth mexptuple -1)) )
		    (debug "mexpand_match lastmexp lx" lx)
		    lx))
	(:long ix (-i nbmatch 1))
	(caselist (make_list discr_list))
	)
    (debug "mexpand_match mexptuple" mexptuple)
    (forever matchloop
	     (if (<i ix 0) (exit matchloop))
	     (let ( (curmatch (multiple_nth mexptuple ix)) )
	       (debug "mexpand_match curmatch" curmatch)
	       (cond 
		;; handle ordinary (pattern ...) clauses
		( (is_a curmatch class_sexpr)
		  (let ( (curmatchcont (unsafe_get_field :sexp_contents curmatch))
			 (curmatchloc (unsafe_get_field :loca_location curmatch)) 
			 (curmatchpatx (pair_head (list_first curmatchcont)))
			 (curmatchrestpairs (pair_tail (list_first curmatchcont))) 
			 (curpatctx (instance class_pattern_expansion_context
					      :pctx_mexpander mexpander
					      :pctx_pexpander patternexpand_1
					      :pctx_varmap (make_mapobject discr_map_objects 17)
					      :pctx_modctx modctx
					      ))
			 (curpat (let ( (cp (patternexpand_1 curmatchpatx env curpatctx curmatchloc)) )
					(debug "mexpand_match curpat" cp)
					(assert_msg "check curpat" cp)
					cp))
			 (curbody (expand_pairlist_as_tuple curmatchrestpairs env mexpander modctx))
			 (curcase (instance class_source_match_case
					    :loca_location curmatchloc
					    :scam_patt curpat
					    :scam_body curbody))
			 )
		    (debug "mexpand_match curcase" curcase)
		    (list_prepend caselist curcase)
		    ))
		;; detect non-sexp clauses
		(:else
		 (error_plain loc "(MATCH <expr> <match-case>...) with non sexpr matchcase") 
		 )))
	     (setq ix (-i ix 1)))
    (debug "mexpand_match caselist" caselist)
    (let (
	  (casetupl  (list_to_multiple caselist discr_multiple))
	  (lastcase (multiple_nth casetupl -1))
	  (smat (instance class_source_match
			   :loca_location loc
			   :smat_matchedx matsx
			   :smat_cases casetupl) 
		 )
	  )
      ;; inform the user if the last match clause is not a joker
      (if (is_not_a 
	   (get_field :scam_patt lastcase) 
	   class_source_pattern_joker_variable)
	  (inform_plain loc "last (MATCH ...) clause is not a joker"))
      ;;;
      (debug "mexpand_match result smat" smat)
      (return smat)
      )))

(install_initial_macro 'match mexpand_match)
(export_macro match mexpand_match
 :doc #{The $MATCH syntax is for pattern-matching expressions. Syntax
 is (MATCH <matched-expression> <match-case>...). Each match-case
 starts with a pattern followed by expressions. The catch-all pattern
 @code{?_} should appear in the last match-case if any. Pattern variables
 like @code{?x} are bound by the matching in their match-case.}#)


;;; matchalt is like match 

;;;; the matchalt expander
(defun mexpand_matchalt (sexpr env mexpander modctx)
  (debug "mexpand_matchalt sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(msexp (pair_head (pair_tail (list_first cont))))
	(matsx (mexpander msexp env mexpander modctx))
	(mexptuple (pairlist_to_multiple 
		    (pair_tail (pair_tail (list_first cont)))
		    discr_multiple
		    (lambda (c)
		      (if (is_not_a c class_sexpr)
			  (error_plain loc "MATCHALT with non-sexpr"_))
		      c
		      ))) 
	(:long nbmatch (multiple_length mexptuple))
	(lastmexp (let ( (lx (multiple_nth mexptuple -1)) )
		    (debug "mexpand_matchalt lastmexp lx" lx)
		    lx))
	(:long ix (-i nbmatch 1))
	(caselist (make_list discr_list))
	)
    (debug "mexpand_matchalt mexptuple" mexptuple)
    (forever matchloop
	     (if (<i ix 0) (exit matchloop))
	     (let ( (curmatch (multiple_nth mexptuple ix)) )
	       (debug "mexpand_matchalt curmatch" curmatch)
	       (cond 
		;; handle ordinary (pattern ...) clauses
		( (is_a curmatch class_sexpr)
		  (let ( (curmatchcont (unsafe_get_field :sexp_contents curmatch))
			 (curmatchloc (unsafe_get_field :loca_location curmatch)) 
			 (curmatchpatx (pair_head (list_first curmatchcont)))
			 (curmatchrestpairs (pair_tail (list_first curmatchcont))) 
			 (curpatctx (instance class_pattern_expansion_context
					      :pctx_mexpander mexpander
					      :pctx_pexpander patternexpand_1
					      :pctx_varmap (make_mapobject discr_map_objects 17)
					      :pctx_modctx modctx
					      ))
			 (curpat (let ( (cp (patternexpand_1 curmatchpatx env curpatctx curmatchloc)) )
					(debug "mexpand_matchalt curpat" cp)
					(assert_msg "check curpat" cp)
					cp))
			 (curbody (expand_pairlist_as_tuple curmatchrestpairs env mexpander modctx))
			 (curcase (instance class_source_match_case
					    :loca_location curmatchloc
					    :scam_patt curpat
					    :scam_body curbody))
			 )
		    (debug "mexpand_matchalt curcase" curcase)
		    (list_prepend caselist curcase)
		    ))
		;; detect non-sexp clauses
		(:else
		 (error_plain loc "(MATCHALT <expr> <match-case>...) with non sexpr matchcase") 
		 )))
	     (setq ix (-i ix 1)))
    (debug "mexpand_matchalt caselist" caselist)
    (let (
	  (casetupl  (list_to_multiple caselist discr_multiple))
	  (lastcase (multiple_nth casetupl -1))
	  (smat (instance class_source_matchalt
			   :loca_location loc
			   :smat_matchedx matsx
			   :smat_cases casetupl) 
		 )
	  )
      ;; inform the user if the last matchalt clause is not a joker
      (if (is_not_a 
	   (get_field :scam_patt lastcase) 
	   class_source_pattern_joker_variable)
	  (inform_plain loc "last (MATCHALT ...) clause is not a joker"))
      ;;;
      (debug "mexpand_matchalt result smat" smat)
      (return smat)
      )))

(install_initial_macro 'matchalt mexpand_matchalt)
(export_macro matchalt mexpand_matchalt
 :doc #{The temporary $MATCHALT syntax is for pattern-matching
 expressions. It is sama as $MATCH but uses an alternative
 implementation. @b{Don't use it} (except for test cases), it will disappear when that better
 implemenation will be fully debugged.}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;; for LET
;; internal routine to make a letbinding, called from mexpand_let
(defun mexpand_letbinding (sexpr env mexpander modctx)
  (debug "mexpand_letbinding" " sexpr=" sexpr "\n.. env=" debug_less env)
  (shortbacktrace_dbg "mexpand_letbinding" 7)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(ctyp quasi_ctype_auto)		
	(var ())
	(expr ())
	(curpair (list_first cont))
	(curarg ())
	)
    (setq curarg (pair_head curpair))
    ;; parse the ctype keyword
    (if (is_a curarg class_keyword)
	(let ( (cty (unsafe_get_field :symb_data curarg)) 
	       (tynam (unsafe_get_field :named_name curarg))
	       )
	  (cond
	   ( (is_not_a cty class_quasi_ctype)
	     (error_at loc "letbinding with invalid type keyword $1"_ tynam))
	   ( (== (get_field :ctype_keyword cty) curarg)
	     (setq ctyp cty))
	   ( (== (get_field :ctype_altkeyword cty) curarg)
	     (setq ctyp cty)
	     (warning_at loc "obsolete alternate ctype $1 keyword in let binding, wanting $2"
			   tynam (get_field :named_name (get_field :ctype_keyword ctyp)))
	     )
	   (:else
	    (error_at loc "let-binding with invalid type keyword $1"_
			tynam)))
	  (setq curpair (pair_tail curpair))
	  (setq curarg (pair_head curpair))
	  ))
    ;; parse the variable
    (cond ( (is_a curarg class_keyword)
	    (error_at loc "let-binding cannot bind keyword $1"_  
			(unsafe_get_field :named_name curarg)))
	  ( (is_a curarg class_symbol)
	    (setq var curarg)
	    (setq curpair (pair_tail curpair))
	    (setq curarg (pair_head curpair))
	    ))
    (if (null var) 
	(error_at loc "missing variable in letbinding"_))
    ;; special case for :macro i.e. quasi_ctype_macro
    ;; syntax of the macro binding (:macro <name> <formals> <body>...)
    (if (== ctyp quasi_ctype_macro)
	(let ( (macformals (lambda_arg_bindings curarg :checkarg env mexpander modctx))
	       (varname (unsafe_get_field :named_name var))
	       (macbody ())
	       (newenv (fresh_env env))
	       )
	  (debug "mexpand_letbinding macformals=" macformals "\n.. newenv=" debug_less newenv)
	  (setq curpair (pair_tail curpair))
	  (if (is_a macformals discr_variadic_formal_sequence)
	      (error_at loc ":macro let-binding $1 cannot be variadic" varname))
	  (if (>i (multiple_length macformals) 4)
	      (error_at loc ":macro $1 let-binding should have at most 4 formals" varname))
	  (foreach_in_multiple
	   (macformals)
	   (curmacformal :long ix)
	   (debug "mexpand_letbinding curmacformal=" curmacformal)
	   (assert_msg "check curmacformal" (is_a curmacformal class_formal_binding) curmacformal)
	   (let ( (curformalname (get_field :named_name (get_field :binder curmacformal))) 
		  )
	     (if (!= (get_field :fbind_type curmacformal) ctype_value)
		 (error_at loc ":macro $1 let-binding should be :value" curformalname))
	     (if (find_env newenv (get_field :binder curmacformal))
		 (error_at loc ":macro $1 formal already bound" curformalname))
	     (put_env newenv curmacformal)
	     ))
	  (setq macbody (expand_pairlist_as_tuple curpair newenv mexpander modctx))
	  (debug "mexpand_letbinding macbody=" macbody)
	  (let ( (smacbind
		  (instance class_source_macro_let_binding
			    :loca_location loc
			    :sletb_binder var 
			    :sletm_macro_formals macformals
			    :sletm_macro_body macbody
			    ))
		 )
	    (debug "mexpand_letbinding smacbind=" smacbind)
	    (return smacbind)
	    )))
    ;;
    (when curarg
      (setq expr (mexpander curarg env mexpander modctx))
      (setq curpair (pair_tail curpair))
      (setq curarg (pair_head curpair))
      (if curarg (error_plain loc "too long letbinding"_))
      )
    (let ( (prevbind (find_env env var)) )
      (cond
       ( (null prevbind) ())
       ( (is_a prevbind class_let_binding)
	 (let ( (prevloc (get_field :letbind_loc prevbind)) )
	   (warning_at loc
			 "local let binding $1 hides upper one"
			 (get_field :named_name var))
	   (if prevloc
	       (warning_at prevloc
			     "here is the hidden binding of $1" 
			     (get_field :named_name var)))
				  
	   ))
       ( (is_a prevbind class_fixed_binding)
	 (warning_at loc
		       "local let binding $1 hides definition"
		       (get_field :named_name var))
	 )
       ))
    (let ( (letb
	    (instance class_source_let_binding
		      :loca_location loc
		      :sletb_type ctyp
		      :sletb_binder var
		      :sletb_expr expr)) )
      (return letb)
      )))



;;; the LET expander itself
(defun mexpand_let (sexpr env mexpander modctx)
  (debug "mexpand_let" " start sexpr=" sexpr " env=" debug_less env
	 "\n.. modctx=" modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(secpair (pair_tail (list_first cont)))
	(restpair (pair_tail secpair))
	(bindexpr (pair_head secpair))
	(sbindlist (cond
		    ( (is_a bindexpr class_sexpr)
		      (get_field :sexp_contents bindexpr))
		    ( (null bindexpr)
		      ())
		    ( (is_list bindexpr)
		      bindexpr)
		    (:else
		     (error_at loc "invalid bindings in LET")
		     ())))
	(letbindlist (make_list discr_list))
	(newenv (fresh_env env))
	(maclist (get_field :mocx_macrolist modctx))
	)
    (debug "mexpand_let" " loc=" loc " cont=" cont "\n.. newenv=" debug_less newenv
	   "\n..sbindlist=" sbindlist "\n.. maclist=" maclist)
    (assert_msg "check sbindlist" (is_list_or_null sbindlist) sbindlist sexpr)
    (each_component_in_list
     sbindlist
     curbindsrc
     (debug "mexpand_let" " curbindsrc=" curbindsrc)
     (let ( (cursbind
	     (cond
	      ( (is_a curbindsrc class_source_any_let_binding)
		;;can happen only if the LET expression comes from some macro
		curbindsrc)
	      ( (is_a curbindsrc class_sexpr)
		(mexpand_letbinding curbindsrc newenv mexpander modctx))
	      (:else
	       (error_at loc "inexpected binding $1 in LET" curbindsrc)
	       ())))
	    )
       (debug "mexpand_let" " cursbind=" cursbind
	      "\n..for curbindsrc=" debug_less curbindsrc)
       (assert_msg "check cursbind" (is_a cursbind class_source_any_let_binding)
		   cursbind curbindsrc sexpr)
       (cond ( (is_a cursbind class_source_let_binding)
	       (let (
		     (sx (unsafe_get_field :sletb_expr cursbind))
		     (letbind (instance class_let_binding
					:binder (unsafe_get_field :sletb_binder cursbind)
					:letbind_type (unsafe_get_field :sletb_type cursbind)
					:letbind_expr sx
					:letbind_loc (or (get_field :loca_location cursbind) loc)))
		     )
		 (debug "mexpand_let" " letbind=" letbind)
		 (put_env newenv letbind)
		 (list_append letbindlist cursbind)
		 (debug "mexpand_let" " letbind-updated newenv=" newenv
			"\n.. for cursbind=" cursbind)
		 )
	       )
	     ( (is_a cursbind class_source_macro_let_binding)
	       (debug "mexpand_let:macro" " loc=" loc "; cursbind=" cursbind)
	       (shortbacktrace_dbg "mexpand_let:macro" 15)
	       (assert_msg "check maclist" (is_list maclist) maclist modctx)
	       (let ( 
		     (macsymb (get_field :sletb_binder cursbind))
		     (macloc (or (get_field :loca_location cursbind) loc))
		     (macformals (get_field :sletm_macro_formals cursbind))
		     (macbody (get_field :sletm_macro_body cursbind))
		     (macbind (instance class_defined_macro_binding
					:binder macsymb
					:mbind_expanser ()
					:mbind_defmacro cursbind
					:mbind_data ()
					))
		     (defmaclet (instance class_source_defmacro_in_let
					  :loca_location loc
					  :sdef_name macsymb
					  :sdef_doc ()
					  :sformal_args macformals
					  :sfun_body macbody
					  :smacro_binding macbind
					  :smacro_sourceletbinding cursbind))
		     (sinstmac (instance class_source_macro_installation
					 :loca_location loc
					 :smacinst_defmacro defmaclet
					 :smacinst_env newenv))
		     )
		 (list_append maclist sinstmac)
		 (debug "mexpand_let:macro"
			" loc=" loc
			"\n.. macbind=" macbind
			"\n.. defmaclet=" defmaclet
			"\n.. updated maclist=" maclist
			"\n.. sinstmac=" sinstmac)
		 (letrec ( (mexpanser
			    (lambda (sexprm envm mexpanderm modctxm)
			      (debug "mexpand_let:mexpanser sexprm=" sexprm
				     "\n.. envm=" debug_more envm
				     "\n.. modctxm=" debug_less modctxm
				     "\n.. mexpanderm=" debug_less mexpanderm
				     "\n.. macbind=" macbind)
			      (shortbacktrace_dbg "mexpand_let:mexpanser" 25)
			      (debug "mexpand_let:mexpanser before melt_delayed_macro_expander"
				     " maclist=" maclist "\n.. macbind=" macbind)
			      (melt_delayed_macro_expander macbind maclist envm mexpanderm modctx)
			      (debug "mexpand_let:mexpanser after melt_delayed_macro_expander"
				     " maclist=" maclist "\n.. macbind=" macbind)
			      (let ( (mclos (get_field :mbind_expanser macbind))
				     (locm (get_field :loca_location sexprm))
				     )
				(debug "mexpand_let:mexpanser"
				       " loc=" loc " locm=" locm
				       "\n.. mclos=" mclos
				       "\n.. mexpanser=" mexpanser
				       "\n.. sexprm=" sexprm)
				;; @@@ NOT SURE
				;; (when (== mclos mexpanser)
				;;  (error_at locm "failed to macro-expand LET :macro $1" macsymb)
				;;  (warning_at loc "failed to expand LET :macro $1 defined here" macsymb)
				;;  (return))
				(multicall 
				 (expmac othermac)
				 (mclos sexprm envm mexpanderm modctxm)
				 (debug "mexpand_let:mexpanser expmac=" expmac " othermac=" othermac)
				 (return expmac othermac)
				 )
				)
			      ))
			   )
		   (debug "mexpand_let:macro" " loc=" loc " mexpanser=" mexpanser "\n.. macbind=" macbind)
		   (put_fields macbind :mbind_expanser mexpanser)
		   (debug "mexpand_let:macro" " loc=" loc " update macbind=" macbind)
		   (put_env newenv macbind)
		   (list_append letbindlist cursbind)
		   (debug "mexpand_let:macro" " letbind-updated newenv=" debug_more newenv
			  "\n.. for cursbind=" cursbind
			  "\n.. macbind=" macbind)
		   (shortbacktrace_dbg "mexpand_let:macro-endletrec-mexpanser" 32)
		   )
		 ))
	     (:else
	      (assert_msg "impossible cursbind" () cursbind curbindsrc)))
       )
     )					; end each_component_in_list
    (debug "mexpand_let" " loc=" loc " final newenv=" debug_more newenv
	   "\n.. restpair=" restpair)
    (let ( (bodytup (expand_pairlist_as_tuple restpair newenv mexpander modctx))
	   (bindtup (list_to_multiple letbindlist discr_multiple))
	   (letr 
	    (instance class_source_let
		      :loca_location loc
		      :slet_bindings bindtup
		      :slet_body bodytup))
	   )
      (debug "mexpand_let" " loc=" loc " result letr=" letr "\n.. modctx=" modctx)
      (return letr)
      )))
;;;
(install_initial_macro 'let mexpand_let)
(export_macro
 let mexpand_let
 :doc #{The $LET syntax is for sequential local bindings of
 expressions. Syntax is (LET ( <binding>... ) <body>...). Each binding
 is an optional ctype such as :long or :gimple or :value
 or :auto (which is the default), followed by a local variable name,
 followed by a single expression. With an :auto type annotation, the
 bound variable takes the type provided by the binding expression. The
 body is a non-empty sequence of expressions, evaluated in an
 environment enriched with the local bindings. The MELT LET syntax is
 sequential, like LET* in Scheme so a variable bound in a previous
 binding can appear in the expression of a later binding.}#)


;;;;;;;;;;;;;;;; install methods to detect recursively constructible
;;;;;;;;;;;;;;;; expressions which can appear in letrec bindings.
(defun yes_recursively_constructible (recv)
  (debug "yes_recursively_constructible recv" recv)
  (return recv))
(install_method class_source_lambda is_recursively_constructible yes_recursively_constructible)
(install_method class_source_instance is_recursively_constructible yes_recursively_constructible)
(install_method class_source_tuple is_recursively_constructible yes_recursively_constructible)
(install_method class_source_list is_recursively_constructible yes_recursively_constructible)




;;;;;;;;;;;;;;;;
;;; the LETREC expander itself
(defun mexpand_letrec (sexpr env mexpander modctx)
  (debug "mexpand_letrec sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(secpair (pair_tail (list_first cont)))
	(restpair (pair_tail secpair))
	(bindexpr (pair_head secpair))
	(newenv (fresh_env env))
	(:long nbind 0)	       ;later set to the number of recbindings
	(bindtup ())   ;later set to the tuple of environment bindings
	(srcbindtup ())	;later set to the tuple of let rec source bindings
	(vartup ())	;later set to the tuple of variables
	(exprtup ()) ;later set to the tuple of bound expressions in bindings
	(bodytup ())
	)
    ;; we are accepting the degenerate case (letrec () ....) 
    (if bindexpr 
	(if (is_a bindexpr class_sexpr) 
	    (let ( (recbindtup 
		    (pairlist_to_multiple 
		     (list_first (unsafe_get_field :sexp_contents bindexpr))
		     discr_multiple
		     (lambda (bx) 
		       (if (is_not_a bx class_sexpr)
			   (error_plain loc "sexpr expected in LETREC binding"))
		       bx)))
		   (:long nbrecbind (multiple_length recbindtup)) 
		   (recsexprtup (make_multiple discr_multiple nbrecbind))
		   )
	      (setq nbind nbrecbind)
	      (setq bindtup (make_multiple discr_multiple nbind))
	      (setq srcbindtup (make_multiple discr_multiple nbind))
	      (setq vartup (make_multiple discr_multiple nbind))
	      (setq exprtup (make_multiple discr_multiple nbind))
	      ;; first loop to compute the tuple of variables and s-expressions
	      (foreach_in_multiple
	       (recbindtup)
	       (curbindexpr :long bindix)
	       (debug "mexpand_letrec firstloop curbindexpr" curbindexpr)
	       (if (is_not_a curbindexpr class_sexpr)
		   ;; error message already given
		   (return))
	       (let ( (curcont (get_field :sexp_contents curbindexpr))
		      (curloc (get_field :loca_location curbindexpr))
		      (curpair (list_first curcont))
		      (curcomp (pair_head curpair))
		      (cursymb ())
		      (cursexpr ())
		      )
		 (cond ( (is_a curcomp class_keyword)
			 (error_plain curloc "keyword invalid in LETREC binding")
			 )
		       ( (is_a curcomp class_symbol)
			 (setq cursymb curcomp)
			 )
		       (:else 
			(error_plain curloc "invalid LETREC binding - expecting (<symbol> <constructive-expr>)"))
		       )
		 (setq curpair (pair_tail curpair))
		 (setq curcomp (pair_head curpair))
		 (if (is_a curcomp class_sexpr)
		     (if (is_a cursymb class_symbol)
			 (progn
			   (setq cursexpr curcomp)
			   (multiple_put_nth recsexprtup bindix cursexpr)
			   (multiple_put_nth vartup bindix cursymb)))
		   ;; else curcomp is not a symbol
		   (error_plain curloc "invalid LETREC binding - missing constructive expression"))
		 (if (pair_tail curpair)
		     (error_plain curloc "invalid LETREC binding - more than two components"))
		 ))
	      (debug "mexpand_letrec recsexprtup after firstloop" recsexprtup)
	      (debug "mexpand_letrec vartup after firstloop" vartup)
;;;
	      ;; second loop to fill the newenv with empty letrec bindings
	      (let ( (envmap (get_field :env_bind newenv)) ;; to ensure no repeated variable in letrec
		     )
		(foreach_in_multiple
		 (vartup)
		 (curvar :long varix)
		 (debug "mexpand_letrec second loop curvar" curvar)
		 (if (mapobject_get envmap curvar)
		     (error_at loc "repeated variable $1 in LETREC binding"
			       (get_field :named_name curvar)))
;;; make the binding
		 (let ( (curbind (instance class_letrec_binding
					   :binder curvar
					   :letbind_type ctype_value
					   :letbind_expr () ;filled later
					   )) 
			)
		   (put_env newenv curbind)
		   (multiple_put_nth bindtup varix curbind)
		   )))
	      (debug "mexpand_letrec bindtup after secondloop" bindtup)
;;;
	      ;; third loop to expand the bound expressions which should be recursively constructible
	      (foreach_in_multiple
	       (recsexprtup)
	       (cursexpr :long expix)
	       (let ( 
		     (curloc (or (get_field :loca_location cursexpr) loc))
		     (curexp (mexpander cursexpr newenv mexpander modctx))
		     (curbind (multiple_nth bindtup expix))
		     )
		 (if (null (is_recursively_constructible curexp))
		     (progn
		       (error_plain curloc "invalid expression in LETREC binding [not recursively constructible]")
		       (return)))
		 (put_fields curbind :letbind_expr curexp)
		 (multiple_put_nth exprtup expix curexp)
		 (let ( (sbind
			 (instance class_source_letrec_binding
				   :loca_location (or (get_field :loca_location curexp) loc)
				   :sletb_type ctype_value
				   :sletb_binder (multiple_nth vartup expix)
				   :sletb_expr curexp
				   )
			 ) )
		   (multiple_put_nth srcbindtup expix sbind)
		   )))
	      (debug "mexpand_letrec exprtup after thirdloop" exprtup)
	      )		;end let recbindtup when bindexpr is an s-expr
	  (error_plain loc "missing letbinding-s in LETREC"_))
      )
    (debug "mexpand_letrec srcbindtup" srcbindtup)
    (setq bodytup (expand_pairlist_as_tuple restpair newenv mexpander modctx))
    (if (<=i (multiple_length bodytup) 0)
	(error_plain loc "empty body in LETREC"))
    (let ( (letr
	    (instance class_source_letrec
		      :loca_location loc
		      :slet_bindings srcbindtup
		      :slet_body bodytup)) )
      (debug "mexpand_letrec result" letr)
      (return letr)
      )))
(install_initial_macro 'letrec mexpand_letrec)
(export_macro letrec mexpand_letrec
 :doc #{The $LETREC syntax is for mutually @b{recursive} local
 bindings. Syntax is (LETREC ( <binding>... ) <body>...). Each binding is
 an optional ctype such as :long or :gimple or :value (which is the
 default), followed by a local variable name, followed by a single
 @b{constructive} expression, like $LAMBDA $INSTANCE $TUPLE $LIST. The
 body is a non-empty sequence of sub-expressions evaluated in an
 augmented environment. MELT LETREC is similar to Scheme's LETREC.}#)

;;;;;;;; for LAMBDA
(defun mexpand_lambda (sexpr env mexpander modctx)
  (debug "mexpand_lambda sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (newenv (fresh_env env))
	 (formals (pair_head curpair))
	 )
    ;; parse the formal arguments
    (if (and (notnull formals) (is_not_a formals class_sexpr))
	(error_plain loc "missing formal argument list in (LAMBDA (arglist...) body...)"_))
    (let ( (argtup (lambda_arg_bindings formals :checkarg env mexpander modctx)) )
      (setq curpair (pair_tail curpair))
      (foreach_in_multiple 
       (argtup)
       (lb :long ix) 
       (assert_msg "check lb" (is_a lb class_formal_binding) lb)
       (put_env newenv lb))
      (let ( (bodytup (expand_pairlist_as_tuple curpair newenv mexpander modctx))
	     (lambr 
	      (instance class_source_lambda
			:loca_location loc
			:slam_argbind argtup
			:slam_body bodytup))
	     ) 
	(return lambr)
	))))
(install_initial_macro 'lambda mexpand_lambda)
(export_macro
 lambda mexpand_lambda
 :doc #{The $LAMBDA syntax is for anonymous functions e.g. closures,
 with closed values (however closing things like :gimple or :long is
 not permitted, you have to box them explicitly as :value-s.). Syntax
 is @code{(LAMBDA ( @var{<formals> ...} ) @var{<body>...})}. The
 formal argument list should have its first formal be a :value. Other
 arguments can be c-typed with keywords like :value :gimple :long
 etc. which applies to all succeeding arguments up to the next ctype
 keyword. The body is a non-empty sequence of expressions. $LAMBDA
 functions can $RETURN a value with possible secondary results. See
 also $MULTICALL. $LAMBDA expressions are @b{constructive} so can
 appear in $LETREC bindings.}# )


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;; for VARIADIC
(defun mexpand_variadic (sexpr env mexpander modctx)
  (debug "mexpand_variadic sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (firstpair (pair_tail (list_first cont))) 
	 (rescont (reference ()))
	 (varbindmap (make_mapobject discr_map_objects (+i 7 (*i 3 (list_length cont)))))
	 (hookfun (lambda (x) 
		    (debug "mexpand_variadic/hookfun rescont set to x" x "; loc=" loc)
		    (set_ref rescont x)))
	 )
    (foreach_pair
     (firstpair)
     (curpaircase curcase)
     (debug "mexpand_variadic curcase=" curcase " loc=" loc)
     (when (is_not_a curcase class_sexpr)
	   (error_plain loc "(VARIADIC variadic-case...) expects a list, so cannot have non-list components.")
	   (return))
     (let (
	   (curcaseloc (unsafe_get_field :loca_location curcase))
	   (curcasecont (unsafe_get_field :sexp_contents curcase))
	   (curcasepair (list_first curcasecont))
	   (casefirst (pair_head curcasepair))
	   (caserest (pair_tail curcasepair))
	   )
       (debug "mexpand_variadic casefirst=" casefirst " curcase=" curcase)
       (cond
	((== casefirst :else)
	 ;; warn if not last
	 (when (pair_tail curpaircase)
	       (error_plain curcaseloc "case (:ELSE ...) should be last in (VARIADIC ...)")
	       (warning_plain loc "This (VARIADIC ...) should have (:ELSE ...) case at last")
	       (return))
	 ;; expand the body
	 (debug "mexpand_variadic caserest=" caserest
		"; curcaseloc=" curcaseloc "; loc=" loc)
	 (let ( (bodytup (expand_pairlist_as_tuple caserest env mexpander modctx))
		 )
	   (debug "mexpand_variadic else bodytup before hookfun " bodytup)
	   (debug "mexpand_variadic hookfun before" hookfun)
	   (shortbacktrace_dbg "mexpand_variadic before calling hookfun for else" 15)
	   (hookfun bodytup)
	   )
	 )
	((or (null casefirst)
	     (is_a casefirst class_sexpr))
	 (debug "mexpand_variadic casefirst=" casefirst)
	 (let ( (args (lambda_arg_bindings casefirst :checkarg env mexpander modctx))
		(newenv (fresh_env env))
		)
	   (debug "mexpand_variadic args" args)
	   (foreach_in_multiple 
	    (args)
	    (fbi :long fix)
	    (assert_msg "check fbi" (is_a fbi class_formal_binding) fbi)
	    (let ( ( fbisymb (get_field :binder fbi)) 
		   )
	      (warn_if_redefined fbisymb newenv loc)
	      (if (mapobject_get varbindmap
				 fbisymb)
		  (error_at curcaseloc "formals should all be distinct in (VARIADIC ...) but $1 is repeated" 
			    (get_field :named_name fbisymb))
		)
	      (mapobject_put varbindmap fbisymb fbi)
	      (put_env newenv fbi)
	      ))
	   (let ( (bodytup (expand_pairlist_as_tuple caserest newenv mexpander modctx))
		  (sifvariadic (instance class_source_ifvariadic
					 :loca_location (or curcaseloc loc)
					 :sifvariadic_argbind args
					 :sifvariadic_then bodytup
					 :sifvariadic_else ()))
		  )
	     (debug "mexpand_variadic bodytup" bodytup " sifvariadic=" sifvariadic " loc=" loc)
	     (shortbacktrace_dbg "mexpand_variadic before calling hookfun for casefirst" 15)
	     (hookfun sifvariadic)
	     (setq hookfun
		   (lambda (xtup) 
		     (debug "mexpand_variadic/hookfun xtup" xtup)
		     (put_fields sifvariadic :sifvariadic_else 
				 (if (is_multiple_or_null xtup) 
				     xtup
				   (tuple xtup)))
		     (debug "mexpand_variadic/hookfun updated sifvariadic" sifvariadic)
		     ))
	     )))
	(:else
	 (debug "mexpand_variadic invalid casefirst" casefirst)
	 (error_plain curcaseloc "invalid case in (VARIADIC ...), should start with formals")
	 (return)
	 )
	)
       )
     (debug "mexpand_variadic done curcase=" curcase)
     )
    (debug "mexpand_variadic final rescont=" rescont " loc=" loc)
    (let ( (res !rescont) 
	   )
      (debug "mexpand_variadic result=" res " loc=" loc)
      (return res)
      )))
(install_initial_macro 'variadic mexpand_variadic)
(export_macro variadic mexpand_variadic
 :doc #{The $VARIADIC syntax is for getting variable arguments inside
variadic functions -using :REST-.  Syntax is 
@code{(VARIADIC @var{variadic-case ...})} where each @var{variadic-case} is
@code{( (@var{formal ...}) @var{body ...})} and the last
@var{variadic-case} can also be @code{(:ELSE @var{body ...})}. When
the actual variable arguments's signature match the given formals in a
@var{variadic-case}, they are bound, and the body of that case is
evaluated. If no @var{formals} match in type and number and if the last
@var{variadic-case} starts with @code{:ELSE} it is exacuted. As an
expression, @code{(VARIADIC @var{...})} gives no result, so is
@code{:void}. In a @var{variadic-case}, if no @var{<formals} are
given, the body is executed when no more actual variable arguments
remain.}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;; for MULTICALL
(defun mexpand_multicall (sexpr env mexpander modctx)
  (debug "mexpand_multicall sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (newenv (fresh_env env))
	 )
    ;; parse the formal results
    (let ( (restup (lambda_arg_bindings (pair_head curpair) :checkarg env mexpander modctx)) 
	   )
      (if (is_a restup discr_variadic_formal_sequence)
	  (progn
	    (error_plain loc "MULTICALL cannot have variadic result")
	    (return)))
      (setq curpair (pair_tail curpair))
      (let ( (curcallexp (pair_head curpair)) )
	(if (not (is_a curcallexp class_sexpr))
	    (error_plain loc "missing called expression in MULTICALL"_))
	(setq curpair (pair_tail curpair))
	(let ( (curcall (mexpander curcallexp env mexpander modctx)) )
	  ;; check the called subexpression
	  (cond 
	   ((or (is_a curcall class_source_apply)
		(is_a curcall class_source_msend)) 
	    ())
	   (:else 
	    (debug "mexpand_multicall bad curcall" curcall)
	    (error_plain loc "called expression in MULTICALL is invalid, expecting application or send")
	    (return)))
	  (multiple_every restup 
			  (lambda (lb) (put_env newenv lb)
			    ))
	  (let ( (bodytup (expand_pairlist_as_tuple curpair newenv mexpander modctx))
		 (mulcr
		  (instance class_source_multicall
			    :loca_location loc
			    :smulc_resbind restup
			    :smulc_call curcall
			    :smulc_body bodytup
			    )) 
		 )
	    (return mulcr)
	    ))))))
(install_initial_macro 'multicall mexpand_multicall)
(export_macro multicall mexpand_multicall
 :doc #{The $MULTICALL syntax is for accumulating the primary and
 secondary results of a function application or a message
 sending. Syntax is @code{(MULTICALL ( @var{<formals>} ) @var{<application-or-message-send>}
 @var{<body>...})}. The first formal is bound to the primary result and
 should be a :value. Other are for secondary results. The body is
 evaluated with these results of the given application or sending
 expression bound by the formals. Inspired by Scheme's
 CALL-WITH-VALUES or CommonLisp's MULTIPLE-VALUE-BIND.}#)



;;;;;;; for BOX
(defun mexpand_box (sexpr env mexpander modctx)
  (debug "mexpand_box start sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (boxedexp (pair_head curpair))
	 )
    (if (pair_tail curpair)
	(error_plain loc "BOX should have only one argument"_))
    (let (
	  (boxed (mexpander boxedexp env mexpander modctx))
	  (src (instance class_source_box
			 :loca_location loc
			 :sboxed boxed))
	  )
      (debug "mexpand_box src=" src)
      (return src)
      )))
(install_initial_macro 'box mexpand_box)
(export_macro
 box mexpand_box
 :doc #{The $BOX syntax is boxing stuff into mutable values. So
 @code{(box 2)} gives the same as @code{(make_integerbox discr_integer
 2)} and if @var{g} is some @i{gimple} stuff, @code{(box g)} gives the
 same as @code{(make_gimple discr_gimple g)} etc... If the argument is
 some value, it makes some reference, instance of $CLASS_REFERENCE,
 from that value.}#)

;;;;;;; for CONSTANT_BOX
(defun mexpand_constant_box (sexpr env mexpander modctx)
  (debug "mexpand_constant_box start sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (boxedexp (pair_head curpair))
	 )
    (if (pair_tail curpair)
	(error_plain loc "CONSTANT_BOX should have only one argument"_))
    (let (
	  (boxed (mexpander boxedexp env mexpander modctx))
	  (src (instance class_source_constant_box
			 :loca_location loc
			 :sboxed boxed))
	  )
      (debug "mexpand_constant_box src=" src)
      (return src)
      )))
(install_initial_macro 'constant_box mexpand_constant_box)
(export_macro
 constant_box mexpand_constant_box
 :doc #{The $CONSTANT_BOX syntax is boxing stuff into constant
 values. So @code{(constant_box 2)} gives the same as
 @code{(make_integerbox discr_constant_integer 2)} and if @var{g} is
 some @i{gimple} stuff, @code{(box g)} gives the same as
 @code{(make_gimple discr_constant_gimple g)} etc...}#)


;;;;;;; for UNBOX
(defun mexpand_unbox (sexpr env mexpander modctx)
  (debug "mexpand_unbox start sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (ubctypk (pair_head curpair))
	 (ubexpr (progn
		   (setq curpair (pair_tail curpair))
		   (pair_head curpair)))
	 )
    (setq curpair (pair_tail curpair))
    (when curpair
      (error_plain loc "UNBOX expects two arguments: (UNBOX <ctype> <expr>)")
      (return))
    (debug "mexpand_unbox ubctypk=" ubctypk " ubexpr=" ubexpr)
    (when (is_not_a ubctypk class_keyword)
      (error_plain loc "first argument to UNBOX should be a ctype keyword like :tree ....")
      (return))
    (let ( (ctyp (get_field :symb_data ubctypk))
	   )
      (when (is_not_a ctyp class_ctype)
	(error_plain loc "first argument to UNBOX should be a ctype")
	(return))
      (debug "mexpand_unbox ctyp=" ctyp)
      (let ( (mexp (mexpander ubexpr env mexpander modctx))
	     (sunbox (instance class_source_unbox
			       :loca_location loc
			       :sunbox_ctype ctyp
			       :sunbox_expr mexp
			       ))
	     )
	(debug "mexpand_unbox mexp=" mexp " sunbox=" sunbox)
	(return sunbox)
	))))
(install_initial_macro 'unbox mexpand_unbox)
(export_macro
 unbox mexpand_unbox
 :doc #{The $UNBOX syntax is unboxing some value into some raw
 stuff. It is given a ctype and an expression: @code{(UNBOX
 @var{ctype} @var{expr})}.}#)


;;;;;;;; for COMMENT (only of strings)
(defun mexpand_comment  (sexpr env mexpander modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (comstr (pair_head curpair))
	 )
    (if (pair_tail curpair)
	(warning_plain loc "COMMENT should have only one string argument"_))
    (if (not (is_string comstr))
	(progn
	  (warning_plain loc "COMMENT without string is ignored"_)
	  (return)
	  )
      )
    (let ( (scom (instance class_source_comment
			   :loca_location loc
			   :scomm_str comstr)) )
      (return scom)
      )))
(install_initial_macro 'comment mexpand_comment)
(export_macro comment mexpand_comment
 :doc #{The $COMMENT syntax inserts comment in the generated code, or
 skips MELT code. Syntax is (COMMENT <string>) to insert a comment in
 the generated C code, or (COMMENT ...) to skip some syntax.}#)

;;;;;;;;;;;;;;;;
;;;;;;;; for CHEADER
(defun mexpand_cheader  (sexpr env mexpander modctx)
  (debug "mexpand_cheader sexpr=" sexpr "\n.. modctx=" debug_less modctx)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (chead (pair_head curpair))
	 )
    (if (pair_tail curpair)
	(warning_plain loc "CHEADER should have only one argument"))
    (debug "mexpand_cheader chead=" chead "\n.. loc=" loc)
    (cond
     ((is_string chead)
      (void)
      )
     ((is_a chead class_sexpr_macrostring)
      (let ( (sbuf (make_strbuf discr_strbuf))
	     (scont (get_field :sexp_contents chead))
	     (sloc (get_field :loca_location chead))
	     )
	(if sloc (setq loc sloc))
	(foreach_pair_component_in_list
	 (scont)
	 (curpair curarg)
	 (add2out sbuf curarg)
	 )
	(setq chead (strbuf2string discr_verbatim_string sbuf))
	))
     (:else
      (error_plain loc "CHEADER without string or macrostring"_)
      (return)
      )
     )
    (shortbacktrace_dbg "mexpand_cheader" 8)
    (let ( (sch (instance class_source_cheader
			  :loca_location loc
			  :sc_codestring chead)) )
      (debug "mexpand_cheader gives sch=" sch)
      (return sch ())
      )))
(install_initial_macro 'cheader mexpand_cheader)
(export_macro cheader mexpand_cheader
 :doc #{The $CHEADER syntax inserts C code in the header part of the generated code.}#)


;;;;;;;;;;;;;;;;
;;;;;;;; for CIMPLEMENT
(defun mexpand_cimplement  (sexpr env mexpander modctx)
  (debug "mexpand_cimplement sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (chead (pair_head curpair))
	 )
    (if (pair_tail curpair)
	(warning_plain loc "CIMPLEMENT should have only one argument"))
    (debug "mexpand_cimplement chead=" chead)
    (cond
     ((is_string chead)
      (void)
      )
     ((is_a chead class_sexpr_macrostring)
      (let ( (sbuf (make_strbuf discr_strbuf))
	     (scont (get_field :sexp_contents chead))
	     (sloc (get_field :loca_location chead))
	     )
	(if sloc (setq loc sloc))
	(foreach_pair_component_in_list
	 (scont)
	 (curpair curarg)
	 (add2out sbuf curarg)
	 )
	(setq chead (strbuf2string discr_verbatim_string sbuf))
	))
     (:else
      (error_plain loc "CIMPLEMENT without string or macrostring"_)
      (return)
      )
     )
    (let ( (sch (instance class_source_cimplement
			  :loca_location loc
			  :sc_codestring chead)) )
      (debug "mexpand_cimplement gives sch=" sch)
      (return sch)
      )))
(install_initial_macro 'cimplement mexpand_cimplement)
(export_macro cimplement mexpand_cimplement
 :doc #{The $CIMPLEMENT syntax inserts C code in the implementation part of the generated code.}#)


;;;;;;;;;;;;;;;;
;;;;;;;; for MODULE_IS_GPL_COMPATIBLE
(defun mexpand_module_is_gpl_compatible  (sexpr env mexpander modctx)
  (debug "mexpand_module_is_gpl_compatible sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (chead (pair_head curpair))
	 )
    (if (pair_tail curpair)
	(warning_plain loc "MODULE_IS_GPL_COMPATIBLE should have only one argument"))
    (debug "mexpand_module_is_gpl_compatible chead=" chead)
    (cond
     ((is_string chead)
      (void)
      )
     ((is_a chead class_sexpr_macrostring)
      (let ( (sbuf (make_strbuf discr_strbuf))
	     (scont (get_field :sexp_contents chead))
	     (sloc (get_field :loca_location chead))
	     )
	(if sloc (setq loc sloc))
	(foreach_pair_component_in_list
	 (scont)
	 (curpair curarg)
	 (add2out sbuf curarg)
	 )
	(setq chead (strbuf2string discr_verbatim_string sbuf))
	))
     ((is_a chead class_symbol)
      (setq chead (get_field :named_name chead))
      (assert_msg "check symbol name" (is_string chead) chead))
     (:else
      (error_plain loc "MODULE_IS_GPL_COMPATIBLE without string or macrostring"_)
      (return)
      )
     )
    (let ( (sch (instance class_source_module_is_gpl_compatible
			  :loca_location loc
			  :sc_codestring chead)) )
      (debug "mexpand_module_is_gpl_compatible gives sch=" sch)
      (return sch)
      )))
(install_initial_macro 'module_is_gpl_compatible mexpand_module_is_gpl_compatible)
(export_macro module_is_gpl_compatible mexpand_module_is_gpl_compatible
 :doc #{The $MODULE_IS_GPL_COMPATIBLE syntax reminds that MELT modules
 should be GPL compatible. Argument is a comment-like string or
 symbol. This has a role analogue to the
 @code{plugin_is_GPL_compatible} symbol in GCC plugins.}#)


;;;;;;;;;;;;;;;;
;;; for USE_PACKAGE_FROM_PKG_CONFIG

(defun mexpand_use_package_from_pkg_config  (sexpr env mexpander modctx)
  (debug "mexpand_use_package_from_pkg_config sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (xargtup (expand_restlist_as_tuple cont env mexpander modctx))
	 (cmdbuf (make_strbuf discr_strbuf))
	 )
    (debug "mexpand_use_package_from_pkg_config xargtup=" xargtup)
    (add2out cmdbuf "pkg-config --exists")
    (foreach_in_multiple
     (xargtup)
     (curpkgname :long pkgix)
     (unless 
	 (is_string curpkgname)
       (error_plain loc "invalid argument to (USE_PACKAGE_FROM_PKG_CONFIG <pkg-name>...), expecting string")
       (return)
       )
     (let ( (:long goodpkgname 1)
	    )
       (code_chunk checkpkgname_chk #{/* mexpand_use_package_from_pkg_config $CHECKPKGNAME_CHK */ {
		   const char* pkgs_$CHECKPKGNAME_CHK
                      = melt_string_str ((melt_ptr_t) $CURPKGNAME) ;
		   if (!pkgs_$CHECKPKGNAME_CHK) 
                      $GOODPKGNAME = 0 ;
		     else {
		   const char* pc = NULL;
		   for (pc = pkgs_$CHECKPKGNAME_CHK   ; 
			   *pc && $GOODPKGNAME   ; 
			   pc++)
		   {
		   if (ISALNUM(*pc) || *pc == '+' || *pc == '-' || *pc == '_' || *pc == '.' || *pc == '@')
		   continue ;
		   else $GOODPKGNAME = 0L ;
		   }
		   } ;
		   } /* end mexpand_use_package_from_pkg_config $CHECKPKGNAME_CHK */ }#)
       (unless goodpkgname
	 (error_at loc "invalid package name $1 for (USE_PACKAGE_FROM_PKG_CONFIG ...)" curpkgname)
	 (return))
       (add2out cmdbuf " " curpkgname)
       )
     ) ;; end foreach_in_multiple
    ;; check by running pkg-config --exists that the package are existing
    (let ( (cmdstr (strbuf2string discr_string cmdbuf))
	   (:long failcmd 0)
	   )
      (debug "mexpand_use_package_from_pkg_config cmdstr=" cmdstr)
      (code_chunk testpkgconfig_chk #{ /* mexpand_use_package_from_pkg_config $TESTPKGCONFIG_CHK */ {
		  const char* cmd_$TESTPKGCONFIG_CHK = 
		    melt_string_str ((melt_ptr_t) $CMDSTR) ;
		  fflush (NULL)	;
		  $FAILCMD = (cmd_$TESTPKGCONFIG_CHK 
			      ? system (cmd_$TESTPKGCONFIG_CHK) 
			      : 1000) ;
		  } /* end mexpand_use_package_from_pkg_config $TESTPKGCONFIG_CHK */
		  }#)
      (debug "mexpand_use_package_from_pkg_config failcmd=" failcmd)
      (when failcmd
	(error_at loc "unexistent package names for USE_PACKAGE_FROM_PKG_CONFIG $1" cmdstr)
	(return))
      )
    ;; return the source 
    (let ( (sup (instance class_source_use_package_from_pkg_config
			  :loca_location loc
			  :susepackage_pkgtuple xargtup)) )
      (debug "mexpand_use_package_from_pkg_config gives sup=" sup)
      (return sup)
    )))

(install_initial_macro 'use_package_from_pkg_config mexpand_use_package_from_pkg_config)
(export_macro use_package_from_pkg_config mexpand_use_package_from_pkg_config
 :doc #{The @code{$USE_PACKAGE_FROM_PKG_CONFIG} or
 @code{$USE-PACKAGE-FROM-PKG-CONFIG} syntax enables usage of
 @code{pkg-config}-ured packages. Arguments are strings naming
 packages. This modifies the compilation and linking of generated C
 code. Probably using some $CHEADER for some @code{#include} is useful.}#)
(export_macro use-package-from-pkg-config mexpand_use_package_from_pkg_config
 :doc #{The $USE-PACKAGE-FROM-PKG-CONFIG or
 $USE_PACKAGE_FROM_PKG_CONFIG syntax enables usage of
 @code{pkg-config}-ured packages. Arguments are strings naming
 packages. This modifies the compilation and linking of generated C
 code. Probably using some $CHEADER for some @code{#include} is useful.}#)

;;;;;;;;;;;;;;;;
;;;;;;;; for PROGN

;; internal routine to make a return from a pairlist at a location
(defun pairlist_to_return (pair loc env mexpander modctx)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (bodytup (expand_pairlist_as_tuple pair env mexpander modctx))
	 )
    (instance class_source_return
	      :loca_location loc
	      :sargop_args bodytup
	      )
    ))

;;;; the progn expanser
(defun mexpand_progn (sexpr env mexpander modctx)
  (debug "mexpand_progn sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (let ( (sloc (unsafe_get_field :loca_location sexpr))
	 (pairs  (pair_tail
		  (list_first (unsafe_get_field :sexp_contents sexpr)))) 
	 )
    (if (not (is_pair pairs))
	(progn
	  (error_plain sloc "empty PROGN"_)
	  (return)))
    (let ( (progr
	    (pairlist_to_progn pairs
			       sloc
			       env
			       mexpander
			       modctx)) )
      (return progr)
      )))
(install_initial_macro 'progn mexpand_progn)
(export_macro progn mexpand_progn
 :doc #{The $PROGN syntax evaluate a sequence of expressions ignoring
 all but the last which is the result. Syntax is (PROGN
 <expression>...).}# )

;;;; the return expanser
(defun mexpand_return (sexpr env mexpander modctx)
  (debug "mexpand_return sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (retr
	  (pairlist_to_return (pair_tail (list_first (unsafe_get_field :sexp_contents sexpr)))
			      (unsafe_get_field :loca_location sexpr)
			      env
			      mexpander
			      modctx)) 
	 )
    (return retr)
    ))
(install_initial_macro 'return mexpand_return)
(export_macro return mexpand_return
 :doc #{The $RETURN syntax is for returning a primary and possibly
 secondary results. Syntax is (RETURN <expression>...). If no
 expression is given, returns nil. Hooks cannot return secondary results.}#)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; the forever expanser
(defun mexpand_forever (sexpr env mexpander modctx)
  (debug "mexpand_forever sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (slabnam (pair_head curpair))
	 (xlabnam (mexpander slabnam env mexpander modctx))
	 (newenv (fresh_env env))
	 )
    (if (is_not_a xlabnam class_symbol)
	(progn
	  (error_plain loc "missing label in FOREVER"_)
	  (return ())))
    (setq curpair (pair_tail curpair))
    (let ( (labind (instance class_label_binding
			     :binder xlabnam
			     :labind_loc loc)) )
      (put_env newenv labind)
      (let ( (bodytup (expand_pairlist_as_tuple curpair newenv mexpander modctx))
	     (forr
	      (instance class_source_forever
			:loca_location loc
			:slabel_bind labind
			:sfrv_body bodytup)) 
	     )
	(return forr)
	))))
(install_initial_macro 'forever mexpand_forever)
(export_macro
 forever mexpand_forever
 :doc #{The $FOREVER syntax is for infinite loops exited thru
 $EXIT. Syntax is (FOREVER <loop-name> <expr>...). Use $EXIT to go out
 of the loop with a result.}#)


;;;;;;;;;;;;;;;;
;;;; the exit expanser
(defun mexpand_exit (sexpr env mexpander modctx)
  (debug "mexpand_exit sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (slabnam (pair_head curpair))
	 (xlabnam (mexpander slabnam env mexpander modctx))
	 (newenv (fresh_env env))
	 )
    (if (is_not_a xlabnam class_symbol)
	(progn
	  (error_plain loc "missing label in EXIT"_)
	  (return ())))
    (setq curpair (pair_tail curpair))
    (let ( (labind (find_env env xlabnam)) )
      (when (is_not_a labind class_label_binding)
	    (error_at loc "bad label in EXIT $1"_
			(unsafe_get_field :named_name xlabnam))
	    (return ()))
      (let ( (bodytup (expand_pairlist_as_tuple curpair newenv mexpander modctx))
	     (exr
	      (instance class_source_exit
			:loca_location loc
			:slabel_bind labind
			:sexi_body bodytup)) 
	     )
	(return exr)
	))))
(install_initial_macro 'exit mexpand_exit)
(export_macro
 exit mexpand_exit
 :doc #{The $EXIT syntax is for exiting a local $FOREVER loop in the
 same function. Syntax is @code{(EXIT @var{<loop-name>} @var{<expression>...})}.}#)

;;;;;;;;;;;;;;;; 
;;;; the again expander
(defun mexpand_again (sexpr env mexpander modctx)
  (debug "mexpand_again sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (slabnam (pair_head curpair))
	 (xlabsymb (mexpander slabnam env mexpander modctx))
	 )
    (setq curpair (pair_tail curpair))
    (when (is_not_a xlabsymb class_symbol)
	    (error_plain loc "bad label in (AGAIN <label>)"_)
	    (return))
    (when curpair
	  (error_plain loc "extra operands to (AGAIN <label>)")
	  (return))
    (let ( (labind (find_env env xlabsymb)) )
      (when (is_not_a labind class_label_binding)
	    (error_at loc "bad label in AGAIN $1"_
			(unsafe_get_field :named_name xlabsymb))
	    (return))
    (let ( (magain (instance class_source_again
			:loca_location loc
			:slabel_bind labind
			     ))
		 )
      (debug "mexpand_again result" magain)
      (return magain)
))))

(install_initial_macro 'again mexpand_again)
(export_macro
 again mexpand_again
 :doc #{The $AGAIN syntax is for restarting a local $FOREVER loop in the
 same function. Syntax is @code{(AGAIN @var{<loop-label>})}.}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; compile time warning (compile_warning msg expr)
;; we don't issue the warning at expansion phase, but at normalization phase.
(defun mexpand_compile_warning (sexpr env mexpander modctx)
  (debug "mexpand_compile_warning sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (smsg (pair_head curpair))
	 (xmsg (mexpander smsg env mexpander modctx))
	 )
    (if (not (is_string xmsg))
	(progn
	  (error_at loc "missing message string in (COMPILE_WARNING <msg> <exp>)"_)
	  (return ())))
    (setq curpair (pair_tail curpair))
    (let ( (sexp (pair_head curpair))
	   (xexp (mexpander sexp env mexpander modctx))
	   )
      (setq curpair (pair_tail curpair))
      (if (notnull curpair)
	  (error_at loc "too many arguments in (COMPILE_WARNING <msg> [<exp>])"_))
      (let ( (res (instance  class_source_compile_warning
			     :loca_location loc
			     :scdiag_msg xmsg
			     :scdiag_expr xexp
			     ))
	     )
	(debug "mexpand_compile_warning result" res)
	(return res)
	))))
(install_initial_macro 'compile_warning mexpand_compile_warning)
(export_macro compile_warning mexpand_compile_warning
 :doc #{The $COMPILE_WARNING syntax issues a warning, inspired by GCC
 #warning. Syntax is (COMPILE_WARNING <string> [<expression>]).}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; compile time error (compile_error msg expr)
;; we don't issue the error at expansion phase, but at normalization phase.
(defun mexpand_compile_error (sexpr env mexpander modctx)
  (debug "mexpand_compile_error sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (let ( (cont (unsafe_get_field :sexp_contents sexpr))
	 (loc  (unsafe_get_field :loca_location sexpr))
	 (curpair (pair_tail (list_first cont))) 
	 (smsg (pair_head curpair))
	 (xmsg (mexpander smsg env mexpander modctx))
	 )
    (if (not (is_string xmsg))
	(progn
	  (error_at loc "missing message string in (COMPILE_ERROR <msg> <exp>)"_)
	  (return ())))
    (setq curpair (pair_tail curpair))
    (let ( (sexp (pair_head curpair))
	   (xexp (mexpander sexp env mexpander modctx))
	   )
      (setq curpair (pair_tail curpair))
      (if (notnull curpair)
	  (error_at loc "too many arguments in (COMPILE_ERROR <msg> [<exp>])"_))
      (let ( (res (instance  class_source_compile_error
			     :loca_location loc
			     :scdiag_msg xmsg
			     :scdiag_expr xexp
			     ))
	     )
	(debug "mexpand_compile_error result" res)
	(return res)
	))))
(install_initial_macro 'compile_error mexpand_compile_error)
(export_macro compile_error mexpand_compile_error
 :doc #{The $COMPILE_ERROR syntax issues an error, inspired by GCC
 #error. Syntax is (COMPILE_ERROR <string> [<expression>]). May be
 useful in macros or with $GCCIF.}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; assert_msg macro is expanded into other src..
;;;;;; (assert_msg msg check ...)
;;; becomes
;;;;;; (cppif MELT_HAVE_DEBUG (if check (melt_assert_failure_fun () msg filename lineno ...)) ())
;;; where melt_assert_failure_fun is a function.

(defun mexpand_assert_msg (sexpr env mexpander modctx)
  (debug "mexpand_assert_msg sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(xmsg (mexpander (pair_head curpair)  env mexpander modctx))
	(xtest ())
	(xarglist ())
	(assfail_binding (find_env env 'melt_assert_failure_fun))
	)
    (if (not (is_string xmsg))
	(error_plain loc "non string message in (ASSERT_MSG <msg> <test>)"_))
    (setq curpair (pair_tail curpair))
    (cond ( (is_pair curpair)
	    (setq xtest (mexpander (pair_head curpair) env mexpander modctx))
	    (setq xarglist (expand_pairlist_as_list (pair_tail curpair) env mexpander modctx))
	    )
	  (:else
	   (warning_strv loc "empty ASSERT_MSG" xmsg)
	   ))
    (let (
	  (assfailfun 
	   (cond 
	    ( (null assfail_binding)
	      (error_plain loc "unbound MELT_ASSERT_FAILURE in (ASSERT_MSG <msg> <test>)"_)
	      (debug "mexpand_assert_msg  without MELT_ASSERT_FAILURE env=" env
		     " env's class" (discrim env)
		     "find_env giving:" (find_env_debug env 'melt_assert_failure_fun)
		     "'melt_assert_failure_fun=" 'melt_assert_failure_fun)
	      (assert_msg "assfail_binding nul! @@" ())
	      (return))
	    ( (is_a assfail_binding class_function_binding)
	      (or 
	       (unsafe_get_field :fixbind_data assfail_binding)
	       (unsafe_get_field :fubind_defun assfail_binding))
	       )
	    ( (and (is_a assfail_binding class_value_binding)
		   (is_closure (unsafe_get_field :vbind_value assfail_binding)))
	      (unsafe_get_field :vbind_value assfail_binding))
	    (:else
	     (debug "mexpand_assert_msg bad assfail_binding=" assfail_binding)
	     (error_plain loc "MELT_ASSERT_FAILURE badly bound in  (ASSERT_MSG <msg> <test>)"_)
	     (return)
	     )))
	  (filnam (cond
		   ((is_mixint loc) (mixint_val loc))
		   ((is_mixloc loc) (mixloc_val loc))))
	  (afapply (instance 
		  class_source_apply
		  :loca_location loc
		  :sapp_fun 'melt_assert_failure_fun
		  :sargop_args (list_to_multiple 
				(list_append2list
				 (list
				  ()
				  xmsg
				  filnam
				  (make_integerbox discr_integer (get_int loc)))
				 xarglist
				))
		  )
		  )
	  (atest (instance
		  class_source_ifelse
		  :loca_location loc
		  :sif_test xtest
		  :sif_then ()
		  :sif_else afapply))
	  (acppif (instance class_source_cppif
			    :loca_location loc
			    :sifp_cond 'MELT_HAVE_DEBUG
			    :sifp_then atest
			    :sifp_else ()
			    )) 
	  )
      (debug "mexpand_assert_msg result acppif" acppif)
      (return acppif)
      )))
(install_initial_macro 'assert_msg mexpand_assert_msg)
(export_macro assert_msg mexpand_assert_msg
	      :doc #{$ASSERT_MSG macro with a message cstring and an
	      optional condition. Generates an assertion -if
	      MELT_HAVE_DEBUG enabled- and also issues a compile
	      warning if condition is missing so false.}#)



;;;;;; (this_line)  is expand to the literal integer corresponding to the line number;
;;;;; inspired by C++ __LINE__
(defun mexpand_this_line (sexpr env mexpander modctx)
  (debug "mexpand_this_line sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(:long dline (get_int loc))
	)
    (debug "mexpand_this_line dline=" dline)
    (return (if (>i dline 0)
		(constant_box dline))
	    ())))

(install_initial_macro 'this_line mexpand_this_line)
(export_macro this_line mexpand_this_line
	      :doc #{$THIS_LINE, inspired by the @code{__LINE__} macro
	      of C or C++, is a macro expanding to the line number in
	      the source file of its occurrence, or NIL if no line.}#)


;;;;;; (this_file)  is expand to the literal integer corresponding to the line number;
;;;;; inspired by C++ __FILE__
(defun mexpand_this_file (sexpr env mexpander modctx)
  (debug "mexpand_this_file sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(dfilnam (cond
		  ((is_mixint loc) (mixint_val loc))
		  ((is_mixloc loc) (mixloc_val loc))))
	)
    (debug "mexpand_this_file dfilnam=" dfilnam)
    (return dfilnam)))
(install_initial_macro 'this_file mexpand_this_file)
(export_macro this_file mexpand_this_file
	      :doc #{$THIS_FILE, inspired by the @code{__FILE__} macro
	      of C or C++, is a macro expanding to the string naming
	      the source file of its occurrence, or NIL if no source location is available.}#)


;;;;;; (debug ...) 
;;; becomes
;;;;;; (cppif MELT_HAVE_DEBUG (if (melt_need_dbg 0) (melt_debug_fun () count filename lineno ...)))
;;; where count is (melt_callcount) 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mexpand_debug  (sexpr env mexpander modctx)
  (debug "mexpand_debug sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(dfilnam (cond
		  ((is_mixint loc) (mixint_val loc))
		  ((is_mixloc loc) (mixloc_val loc))))
	(:long dline (get_int loc))
	(debugfunbind (find_env env 'melt_debug_fun))
	(thecountbind (find_env env 'melt_callcount))
	(theneeddbgbind (find_env env 'melt_need_dbg))
	(theincrdbgbind (find_env env 'melt_increment_dbgcounter))
	(curpair (pair_tail (list_first cont)))
	(xarglist (expand_pairlist_as_list curpair env mexpander modctx))
	(dbgarglist (list ()))
	)
    ;;; warn if the debug expr is really heavy
    (let ( (sexpw (s_expr_weight sexpr)) 
	   (:long nbsepw (get_int sexpw))
	   )
      (if (or
	   (>i nbsepw 26)
	   (null sexpw))
	  (warning_strv loc
			"suspicious very heavy (DEBUG ....)"
			(string4out discr_string "weight:" sexpw))))
    ;;;
    (if (not (is_string dfilnam))
	(progn
	  (error_plain loc "(DEBUG ...) used without file location")
	  (return)))
    (if (not (or (is_a debugfunbind class_function_binding)
		 (is_a debugfunbind class_value_binding)))
	(progn
	(error_plain loc "(DEBUG ...) used in context with bad MELT_DEBUG_FUN")
	(return)))
    (let (
	  (thecountprim 
	   (cond 
	    ( (is_a thecountbind class_primitive_binding)
	      (get_field :pbind_primitive thecountbind))
	    ( (is_a thecountbind class_value_binding)
	      (get_field :vbind_value thecountbind))
	    (:else
	     (error_plain loc "(DEBUG ...) used in context with bad THE_MELTCALLCOUNT")
	     (return))))
	  (dcount (instance class_source_primitive
			    :loca_location loc
			    :sprim_oper thecountprim
			    :sargop_args (tuple)))
	  )
      (list_append dbgarglist dcount)
      )
    (list_append dbgarglist dfilnam)
    (list_append dbgarglist (make_integerbox discr_constant_integer dline))
    (list_append2list dbgarglist xarglist)
    (debug "mexpand_debug dbgarglist" dbgarglist)
    (let (
	  (:long nbdbgarg (list_length dbgarglist))
	  (theneeddbg
	   (cond 
	    ( (is_a theneeddbgbind class_primitive_binding)
	      (get_field :pbind_primitive theneeddbgbind))
	    ( (is_a theneeddbgbind class_value_binding)
	      (get_field :vbind_value theneeddbgbind))
	    (:else
	     (error_plain loc "(DEBUG ...) used in context with bad MELT_NEED_DBG")
	     (return))))
	  (dneedbg (instance class_source_primitive
			     :loca_location  loc
			     :sprim_oper theneeddbg
			     :sargop_args (tuple '0)))
	  (dcall (instance 
		  class_source_apply
		  :loca_location loc
		  :sapp_fun 'melt_debug_fun
		  :sargop_args (list_to_multiple dbgarglist discr_multiple)))
	  (theincrdbg
	   (cond 
	    ( (is_a theincrdbgbind class_primitive_binding)
	      (get_field :pbind_primitive theincrdbgbind))
	    ( (is_a theincrdbgbind class_value_binding)
	      (get_field :vbind_value theincrdbgbind))
	    (:else
	     (error_plain 
	      loc 
	      "(DEBUG ...) used in context with bad MELT_INCREMENT_DBGCOUNTER")
	     (return))))
	  (dincrdbg (instance
		     class_source_primitive
		     :loca_location loc
		     :sprim_oper theincrdbg
		     :sargop_args (tuple)))
	  (difdbg (instance
		   class_source_if
		   :loca_location loc
		   :sif_test dneedbg
		   :sif_then dcall))
	  (dvoid (instance
		  class_source_primitive
		  :loca_location loc
		  :sprim_oper void
		  :sargop_args (tuple)))
	  (dprogn (instance 
		   class_source_progn
		   :loca_location loc
		   :sprogn_body (tuple dincrdbg difdbg dvoid)
		   ))
	  (dcppif (instance class_source_cppif
			    :loca_location loc
			    :sifp_cond 'MELT_HAVE_DEBUG
			    :sifp_then dprogn
			    :sifp_else dvoid
			    )) 
	  )
      ;;
      ;;
      (debug "mexpand_debug dcall=" dcall " return dcppif=" dcppif)
      (return dcppif)
      )))
(install_initial_macro 'debug mexpand_debug)

(export_macro debug mexpand_debug
   :doc #{$DEBUG is a variadic and polytypic macro for debugging
   prints. You can give it arbitrary arguments -either
   stuff or values-. Debugging prints should be enabled at
   compilation time of the generated C code with the
   @code{quicklybuilt} or @code{debugnoline} module
   flavors, and at run time with the
   @code{-f[plugin-arg-]melt-debugging=} option. Internally
   @code{(DEBUG @var{arg...})} is macro expanded to something similar to
   @code{(cppif MELT_HAVE_DEBUG (if (melt_need_dbg 0) (melt_debug_fun ()
   @var{count} @var{filename} @var{lineno} ...)))}}#)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; export_values macro (export_values <symbol> ...)
(defun mexpand_export_values (sexpr env mexpander modctx)
  (debug "mexpand_export_values sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(symbtup (expand_pairlist_as_tuple curpair env mexpander modctx))
	(res (instance class_source_export_values
		       :loca_location loc
		       :sexport_names symbtup))
	)
    (foreach_in_multiple
     (symbtup)
     (cursymb :long six)
     (if (is_not_a cursymb class_symbol)
       (error_at loc "(EXPORT_VALUES <symbol> ...) with non-symbol argument of rank $1" six)))
    (debug "mexpand_export_values result res" res)
    (return res)
    ))
(install_initial_macro 'export_values mexpand_export_values)
(export_macro export_values mexpand_export_values
	      :doc #{$EXPORT_VALUES is a macro to export values
	      defined by names. Give it a sequence of names bound to
	      values using $DEFINE, $DEFUN, $DEFINSTANCE,
	      $DEFSELECTOR, $DEFCITERATOR, $DEFCMATCHER,
	      $DEFFUNMATCHER etc. Use $EXPORT_CLASS for exporting
	      classes and their fields.}#)

;;;;
;;; export_macro macro (export_macro <symbol> <expander> [:doc <documentation>])
;;; or (export_macro <symbol>) for a DEFMACRO-ed symbol
(defun mexpand_export_macro (sexpr env mexpander modctx)
  (debug "mexpand_export_macro sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(symb (mexpander (pair_head curpair) env mexpander modctx))
	(doc ())
	)
    (if (is_not_a symb class_symbol)
	(error_plain loc "(EXPORT_MACRO <sym> [<expander>]) expecting symbol"_))
    (setq curpair (pair_tail curpair))
    (let (
	  (symbname (get_field :named_name symb))
	  (sexpv (let ( (se (pair_head curpair)) 
			)
		   (debug "mexpand_export_macro sexpv=" se)
		   se))
	  (cbind (let ( (cb (find_env env symb))
			)
		   (debug "mexpand_export_macro cbind=" cb)
		   cb))
	  (:long isdefmacro (is_a cbind class_defined_macro_binding))
	  (expv (cond ( (null sexpv)
			(when (not isdefmacro)
			  (error_at loc "(EXPORT_MACRO $1 <expander>) needs an expander for non-defmacro symbol"
				      symbname)
			  (return))
			symb
			)
		      (:else 
		       (mexpander sexpv env mexpander modctx))))
	  )
      (setq curpair (pair_tail curpair))
      (if (== (pair_head curpair) ':doc)
	  (progn
	    (setq curpair (pair_tail curpair))
	    (setq doc (pair_head curpair))))
      (if (null expv)
	  (error_at loc  "(EXPORT_MACRO $1 <expander> [:doc <docum>]) expecting expander"_ symbname))
      (let ( (res (if (and isdefmacro (null sexpv))
		      (instance class_source_export_defmacro
				:loca_location loc
				:sexpmac_mname symb
				:sexpmac_doc doc)
		      (instance class_source_export_macro
			    :loca_location loc
			    :sexpmac_mname symb
			    :sexpmac_doc doc
			    :sexpmac_mval expv
			    )))
	     )
	(debug "mexpand_export_macro result res=" res)
	(return res)
	))))
(install_initial_macro 'export_macro mexpand_export_macro)
(export_macro export_macro mexpand_export_macro
	      :doc #{@code{($EXPORT_MACRO @var{name} @var{macro-expander} [@code{:doc} @var{documentation}])} is used to define an exported macro.}#)




;;;;
;;; export_patmacro macro (export_patmacro <symbol> <patexpander> <macexpander> [:doc <docum>])
(defun mexpand_export_patmacro (sexpr env mexpander modctx)
  (debug "mexpand_export_patmacro sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check mexpander" (is_closure mexpander) mexpander)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(symb (mexpander (pair_head curpair) env mexpander modctx))
	(patexpv ())		    ;set later to the pattern expander
	(macexpv ())		    ;set later to the macro expander
	(doc ())		    ;set later to the documentation if any
	)
    (if (is_not_a symb class_symbol)
	(error_plain loc "(EXPORT_PATMACRO <sym> <patexpander> <macexpander> [:doc <docum>]) expecting symbol"_))
    (setq curpair (pair_tail curpair))
    (setq patexpv (mexpander (pair_head curpair) env mexpander modctx))
    (if (null patexpv)
	(error_plain loc  "(EXPORT_PATMACRO <sym> <patexpander> <macexpander> [:doc <docum>]) expecting patexpander"_))
    (setq curpair (pair_tail curpair))
    (setq macexpv (mexpander (pair_head curpair) env mexpander modctx))
    (if (null macexpv)
	(error_plain loc  "(EXPORT_PATMACRO <sym> <patexpander> <macexpander> [:doc <docum>]) expecting macexpander"_))
    (setq curpair (pair_tail curpair))
    (if (== (pair_head curpair) ':doc)
	(progn
	  (setq curpair (pair_tail curpair))
	  (setq doc (pair_head curpair))
	  ))
    ;;
    (let ( (res (instance class_source_export_patmacro
			  :loca_location loc
			  :sexpmac_mname symb
			  :sexppat_pval patexpv
			  :sexpmac_mval macexpv
			  :sexpmac_doc doc
			  ))
	   )
      (debug "mexpand_export_patmacro result res" res)
      (return res)
      )))
(install_initial_macro 'export_patmacro mexpand_export_patmacro)
(export_macro export_patmacro mexpand_export_patmacro
	      :doc #{@code{($EXPORT_PATMACRO @var{name} @var{pattern-expander} [@var{macro-expander}] [:doc @var{documentation}])} 
is used to define patmacros.}#)

;;;;
;;; export_class macro (export_class <symbol> ...)
(defun mexpand_export_class (sexpr env mexpander modctx)
  (debug "mexpand_export_class sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(symbtup (expand_pairlist_as_tuple curpair env mexpander modctx))
	(res (instance class_source_export_class
		       :loca_location loc
		       :sexport_names symbtup))
	)
    (foreach_in_multiple
     (symbtup)
     (cursymb :long six)
     (if (is_not_a cursymb class_symbol)
       (error_at loc "(EXPORT_CLASS <symbol> ...) with non-symbol argument of rank $1" six)))
    (debug "mexpand_export_class result res" res)
    (return res)
    ))
(install_initial_macro 'export_class mexpand_export_class)
(export_macro export_class mexpand_export_class
	      :doc #{@code{($EXPORT_CLASS @var{names...})} is used to export class and their field names.}#)



;;; export_synonym macro (export_synonym <newname> <oldname>  [:doc <documentation>])
(defun mexpand_export_synonym (sexpr env mexpander modctx)
  (debug "mexpand_export_synonym sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(newsymb ())
	(oldsymb ())
	(doc ())
	)
    ;; handle the newsymb
    (setq newsymb (mexpander (pair_head curpair) env mexpander modctx))
    (debug "mexpander_export_synonym newsymb" newsymb)
    (if (is_not_a newsymb class_symbol)
	(error_plain loc "bad new name in (EXPORT_SYNONYM <newname> <oldname> [:doc <docum>])"))	
    (setq curpair (pair_tail curpair))
    ;; handle the oldsymb
    (setq oldsymb (mexpander (pair_head curpair) env mexpander modctx))
    (debug "mexpander_export_synonym oldsymb" oldsymb)
    (if (is_not_a oldsymb class_symbol)
	(error_plain loc "bad old name in (EXPORT_SYNONYM <newname> <oldname> [:doc <docum>])"))	
    (setq curpair (pair_tail curpair))
    (if (== (pair_head curpair) ':doc)
	(progn
	  (setq curpair (pair_tail curpair))
	  (setq doc (pair_head curpair))
	  ))
    (debug "mexpander_export_synonym doc" doc)
    (let ( 
	  (res (instance class_source_export_synonym
			 :loca_location loc
			 :sexpsyn_newname newsymb
			 :sexpsyn_oldname oldsymb
			 :sexpsyn_doc doc))
	  )
      (debug "mexpander_export_synonym result" res)
      (return res)
      )))
(install_initial_macro 'export_synonym mexpand_export_synonym)
(export_macro export_synonym mexpand_export_synonym
	      :doc #{@code{($EXPORT_SYNONYM @var{new-name} @var{old-name}
					    [:doc @var{documentation}])}
		     is used to define a synonym.
					    }#)


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; current_module_environment_reference macro 
(defun mexpand_current_module_environment_reference (sexpr env mexpander modctx)
  (debug "mexpand_current_module_environment_reference sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(res (instance class_source_current_module_environment_reference
		       :loca_location loc))
	)
    (if (notnull curpair)
	(error_plain loc "(CURRENT_MODULE_ENVIRONMENT_REFERENCE) should not have any argument"_))
    (debug "mexpand_current_module_environment_reference return res" res)
    (return res)
    ))

(install_initial_macro 'current_module_environment_reference mexpand_current_module_environment_reference)
(export_macro current_module_environment_reference mexpand_current_module_environment_reference
	      :doc #{@code{($CURRENT_MODULE_ENVIRONMENT_REFERENCE)}
returns a container, i.e. a reference thru @code{$CLASS_REFERENCE},
for the current environment. See also $PARENT_MODULE_ENVIRONMENT and
$CLASS_ENVIRONMENT. @code{($CURRENT_MODULE_ENVIRONMENT_REFERENCE)}
cannot be used inside hooks. Was previously called inccorrectly
@code{CURRENT_MODULE_ENVIRONMENT_CONTAINER}.}#)

(install_initial_macro 'current_module_environment_container mexpand_current_module_environment_reference)
(export_macro current_module_environment_container mexpand_current_module_environment_reference
	      :doc #{@code{($CURRENT_MODULE_ENVIRONMENT_CONTAINER)} is
	      obsolete. Use $CURRENT_MODULE_ENVIRONMENT_REFERENCE.}#)

;;;;;;;;;;;;;;;;
;;;; parent_module_environment macro 
(defun mexpand_parent_module_environment (sexpr env mexpander modctx)
  (debug "mexpand_parent_module_environment sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(res (instance class_source_parent_module_environment
		       :loca_location loc))
	)
    (if (notnull curpair)
	(error_plain loc "(PARENT_MODULE_ENVIRONMENT) should not have any argument"_))
    (debug "mexpand_parent_module_environment return res" res)
    (return res)
    ))
(install_initial_macro 'parent_module_environment mexpand_parent_module_environment)
(export_macro parent_module_environment mexpand_parent_module_environment
	      :doc #{@code{($PARENT_MODULE_ENVIRONMENT)} gives the
	      parent environnment of this module. See also
	      $CLASS_ENVIRONMENT and
	      $CURRENT_MODULE_ENVIRONMENT_REFERENCE. @code{($PARENT_MODULE_ENVIRONMENT)}
	      cannot be used inside hooks.}#)



;;;;;;;;;;;;;;;;
;;;; update_current_module_environment_reference macro 
(defun mexpand_update_current_module_environment_reference  (sexpr env mexpander modctx)
  (debug "mexpand_update_current_module_environment_reference sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(loc  (unsafe_get_field :loca_location sexpr))
	(cont (unsafe_get_field :sexp_contents sexpr))
	(curpair (pair_tail (list_first cont)))
	(res (instance class_source_update_current_module_environment_reference
		       :loca_location loc))
	)
    (if (notnull curpair)
	(error_plain loc "(UPDATE_CURRENT_MODULE_ENVIRONMENT_REFERENCE) should not have any argument"_))
    (if (not (melt_is_bootstrapping))
	(error_plain loc "(UPDATE_CURRENT_MODULE_ENVIRONMENT_REFERENCE) can only be used while bootstrapping MELT."))
    (debug "mexpand_update_current_module_environment_reference return res" res)
    (return res)
    ))

(install_initial_macro 'update_current_module_environment_reference mexpand_update_current_module_environment_reference)
(export_macro update_current_module_environment_reference mexpand_update_current_module_environment_reference
	      :doc
#{@code{($UPDATE_CURRENT_MODULE_ENVIRONMENT_REFERENCE)} is a guru
macro to update the current module environment reference.  You
probably should never use it, but it is necessary inside MELT. See
$CURRENT_MODULE_ENVIRONMENT_REFERENCE. Was previously called incorrectly
@code{UPDATE_CURRENT_MODULE_ENVIRONMENT_CONTAINER}.}#)

;; compatibility
(install_initial_macro 'update_current_module_environment_container mexpand_update_current_module_environment_reference)
(export_macro update_current_module_environment_container mexpand_update_current_module_environment_reference)

;;;;;;;;;;;;;;;;

(defun mexpand_fetch_predefined (sexpr env mexpander modctx)
  (debug "mexpand_fetch_predefined sexpr" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(spredef (mexpander (pair_head curpair) env mexpander modctx))
	)
    (if (null curpair) 
	(error_plain loc "(FETCH_PREDEFINED <predef-name-or-rank>) missing argument"_))
    (if (notnull (pair_tail curpair))
	(error_plain loc "(FETCH_PREDEFINED <predef-name-or-rank>) extra argument"_))
    (if (not (or (is_a spredef class_symbol) (is_integerbox spredef)))
	(error_plain loc "(FETCH_PREDEFINED <predef-name-or-rank>) invalid argument"_))
    (let ( (res (instance class_source_fetch_predefined
			  :loca_location loc
			  :sfepd_predef spredef)) )
      (debug "mexpand_fetch_predefined result" res)
      (return res)
      )))
(install_initial_macro 'fetch_predefined mexpand_fetch_predefined)
(export_macro fetch_predefined mexpand_fetch_predefined
	      :doc #{@code{($FETCH_PREDEFINED @var{predefined-name})} is accessing a predefined value without using environments. You probably don't need that.}#)

;;;;;;;;;;;;;;;;
(defun mexpand_store_predefined (sexpr env mexpander modctx)
  (debug "mexpand_store_predefined sexpr=" sexpr)
  (assert_msg "check sexpr" (is_a sexpr class_sexpr) sexpr)
  (assert_msg "check env" (is_a env class_environment) env)
  (if (null mexpander) (setq mexpander macroexpand_1))
  (assert_msg "check modctx" (is_object modctx) modctx)
  (let (
	(cont (unsafe_get_field :sexp_contents sexpr))
	(loc  (unsafe_get_field :loca_location sexpr))
	(curpair (pair_tail (list_first cont)))
	(spredef (mexpander (pair_head curpair) env mexpander modctx))
	(sval ())
	)
    (if (null curpair) 
	(error_plain loc "(STORE_PREDEFINED <predef-name-or-rank> <value>) missing predef"_))
    (setq curpair (pair_tail curpair))
    (if (null curpair) 
	(error_plain loc "(STORE_PREDEFINED <predef-name-or-rank> <value>) missing predef"_))
    (setq sval (mexpander (pair_head curpair) env mexpander modctx))
    (if (notnull (pair_tail curpair))
	(error_plain loc "(STORE_PREDEFINED <predef-name-or-rank> <value>) extra argument"_))
    (if (not (or (is_a spredef class_symbol) (is_integerbox spredef)))
	(error_plain loc "(STORE_PREDEFINED <predef-name-or-rank> <value>) invalid predef"_))
    (let ( (res (instance class_source_store_predefined
			  :loca_location loc
			  :sstpd_predef spredef
			  :sstpd_value sval
			  )) )
      (debug "mexpand_store_predefined result" res)
      (return res)
      )))
(install_initial_macro 'store_predefined mexpand_store_predefined)
(export_macro store_predefined mexpand_store_predefined 
	      :doc #{@code{($STORE_PREDEFINED @var{predefined-name} @var{value})} is storing a predefined value. You probably never need that.}#)

;;;;;;;;;;;;;;;;

(export_class  ;classes for source representations, alphabetical order
 class_defined_macro_binding
 class_pattern_expansion_context
 class_source_again
 class_source_any_let_binding
 class_source_apply
 class_source_arithmetic_variadic_operation
 class_source_argumented_operator
 class_source_box
 class_source_cheader
 class_source_cimplement
 class_source_citeration
 class_source_cmatchexpr
 class_source_code_string
 class_source_codechunk
 class_source_comment
 class_source_compile_diagnostic
 class_source_compile_error
 class_source_compile_warning
 class_source_constant_box
 class_source_cppif
 class_source_current_module_environment_reference
 class_source_defciterator
 class_source_defclass
 class_source_defcmatcher
 class_source_defhook
 class_source_define
 class_source_definition
 class_source_definition_formal
 class_source_definstance
 class_source_defobjcommon
 class_source_defprimitive
 class_source_defmacro
 class_source_defmacro_in_let
 class_source_defselector
 class_source_defun
 class_source_defunmatcher
 class_source_defvar
 class_source_exit
 class_source_export_any_macro
 class_source_export_class
 class_source_export_defmacro
 class_source_export_macro
 class_source_export_patmacro
 class_source_export_synonym
 class_source_export_values
 class_source_exportcommon
 class_source_exprchunk
 class_source_fetch_predefined
 class_source_field_pattern
 class_source_fieldassign
 class_source_forever
 class_source_funmatchexpr
 class_source_generator_device
 class_source_get_field
 class_source_hook_call
 class_source_if
 class_source_ifelse
 class_source_ifvariadic
 class_source_instance
 class_source_labelled
 class_source_lambda
 class_source_lambda_for_macro
 class_source_lazy_macro_expansion
 class_source_let
 class_source_let_binding
 class_source_let_binding_for_macro
 class_source_letrec
 class_source_letrec_binding
 class_source_list
 class_source_macro_let_binding
 class_source_macro_installation
 class_source_match
 class_source_match_case
 class_source_matchalt
 class_source_module_is_gpl_compatible
 class_source_msend
 class_source_multicall
 class_source_or
 class_source_parent_module_environment
 class_source_pattern
 class_source_pattern_and
 class_source_pattern_c_match
 class_source_pattern_composite
 class_source_pattern_constant 
 class_source_pattern_construct
 class_source_pattern_instance
 class_source_pattern_joker_variable
 class_source_pattern_list
 class_source_pattern_matcher
 class_source_pattern_object
 class_source_pattern_or
 class_source_pattern_tuple
 class_source_pattern_variable
 class_source_primitive
 class_source_progn
 class_source_protochunk
 class_source_put_fields
 class_source_quasi_box
 class_source_quote
 class_source_return
 class_source_setq
 class_source_store_predefined
 class_source_tuple
 class_source_unbox
 class_source_unsafe_get_field
 class_source_unsafe_put_fields
 class_source_update_current_module_environment_reference
 class_source_use_package_from_pkg_config
 )			       ;end classes for source representations

(export_synonym
 class_source_update_current_module_environment_container class_source_update_current_module_environment_reference
)

(export_synonym
 class_source_current_module_environment_container class_source_current_module_environment_reference
)

(export_values			 ;values for source representations
 expand_apply
 expand_msend  
 expand_pairlist_as_tuple
 expand_pairlist_as_list
 expand_restlist_as_list
 expand_restlist_as_tuple
 expand_tuple_slice_as_tuple 
 expand_primitive
 hook_macro_installer
 install_initial_macro
 install_initial_patmacro
 is_recursively_constructible
 lambda_arg_bindings
 macroexpand_1
 macroexpand_toplevel_list
 melt_register_translator_runner_macroexpansions
 patternexpand_1
 patternexpand_expr
 patternexpand_pairlist_as_tuple
 pattern_weight_tuple
 register_generator_device
 s_expr_weight
 mexpand_reference
 patexpand_reference
 )			  ;end of values for source representations


;; eof warmelt-macro.melt