summaryrefslogtreecommitdiff
path: root/ghc/interpreter/hugs.c
blob: d05cb5117d2fb0b7ae7e781695a86452f07f81ef (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

/* --------------------------------------------------------------------------
 * Command interpreter
 *
 * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
 * Yale Haskell Group, and the Oregon Graduate Institute of Science and
 * Technology, 1994-1999, All rights reserved.  It is distributed as
 * free software under the license in the file "License", which is
 * included in the distribution.
 *
 * $RCSfile: hugs.c,v $
 * $Revision: 1.42 $
 * $Date: 2000/03/13 11:37:16 $
 * ------------------------------------------------------------------------*/

#include <setjmp.h>
#include <ctype.h>
#include <stdio.h>

#include "prelude.h"
#include "storage.h"
#include "connect.h"
#include "errors.h"
#include "version.h"

#include "Rts.h"
#include "RtsAPI.h"
#include "Schedule.h"
#include "Assembler.h"                                /* DEBUG_LoadSymbols */

Bool haskell98 = TRUE;                  /* TRUE => Haskell 98 compatibility*/

#if EXPLAIN_INSTANCE_RESOLUTION
Bool showInstRes = FALSE;
#endif
#if MULTI_INST
Bool multiInstRes = FALSE;
#endif

/* --------------------------------------------------------------------------
 * Local function prototypes:
 * ------------------------------------------------------------------------*/

static Void   local initialize        ( Int,String [] );
static Void   local promptForInput    ( String );
static Void   local interpreter       ( Int,String [] );
static Void   local menu              ( Void );
static Void   local guidance          ( Void );
static Void   local forHelp           ( Void );
static Void   local set               ( Void );
static Void   local changeDir         ( Void );
static Void   local load              ( Void );
static Void   local project           ( Void );
static Void   local readScripts       ( Int );
static Void   local whatScripts       ( Void );
static Void   local editor            ( Void );
static Void   local find              ( Void );
static Bool   local startEdit         ( Int,String );
static Void   local runEditor         ( Void );
static Void   local setModule         ( Void );
static Module local findEvalModule    ( Void );
static Void   local evaluator         ( Void );
static Void   local stopAnyPrinting   ( Void );
static Void   local showtype          ( Void );
static String local objToStr          ( Module, Cell );
static Void   local info              ( Void );
static Void   local printSyntax       ( Name );
static Void   local showInst          ( Inst );
static Void   local describe          ( Text );
static Void   local listNames         ( Void );

static Void   local toggleSet         ( Char,Bool );
static Void   local togglesIn         ( Bool );
static Void   local optionInfo        ( Void );
#if USE_REGISTRY || HUGS_FOR_WINDOWS
static String local optionsToStr      ( Void );
#endif
static Void   local readOptions       ( String );
static Bool   local processOption     ( String );
static Void   local setHeapSize       ( String );
static Int    local argToInt          ( String );

static Void   local loadProject       ( String );
static Void   local clearProject      ( Void );
static Bool   local addScript         ( Int );
static Void   local forgetScriptsFrom ( Script );
static Void   local setLastEdit       ( String,Int );
static Void   local failed            ( Void );
static String local strCopy           ( String );
static Void   local browseit	      ( Module,String,Bool );
static Void   local browse	      ( Void );

/* --------------------------------------------------------------------------
 * Machine dependent code for Hugs interpreter:
 * ------------------------------------------------------------------------*/

       Bool   combined      = TRUE;

#include "machdep.c"
#ifdef WANT_TIMER
#include "timer.c"
#endif

/* --------------------------------------------------------------------------
 * Local data areas:
 * ------------------------------------------------------------------------*/

static Bool   printing      = FALSE;    /* TRUE => currently printing value*/
static Bool   showStats     = FALSE;    /* TRUE => print stats after eval  */
static Bool   listScripts   = TRUE;   /* TRUE => list scripts after loading*/
static Bool   addType       = FALSE;    /* TRUE => print type with value   */
static Bool   useDots       = RISCOS;   /* TRUE => use dots in progress    */
static Bool   quiet         = FALSE;    /* TRUE => don't show progress     */
static Bool   lastWasObject = FALSE;
       Bool   preludeLoaded = FALSE;
       Bool   debugSC       = FALSE;

typedef 
   struct { 
      String modName;                   /* Module name                     */
      Bool   details;             /* FALSE => remaining fields are invalid */
      String path;                      /* Path to module                  */
      String srcExt;                    /* ".hs" or ".lhs" if fromSource   */
      Time   lastChange;                /* Time of last change to script   */
      Bool   fromSource;                /* FALSE => load object code       */
      Bool   postponed;                 /* Indicates postponed load        */
      Bool   objLoaded;
      Long   size;
      Long   oSize;
   }
   ScriptInfo;

static Void   local makeStackEntry    ( ScriptInfo*,String );
static Void   local addStackEntry     ( String );

static ScriptInfo scriptInfo[NUM_SCRIPTS];

static Int    numScripts;               /* Number of scripts loaded        */
static Int    nextNumScripts;
static Int    namesUpto;                /* Number of script names set      */
static Bool   needsImports;             /* set to TRUE if imports required */
       String scriptFile;               /* Name of current script (if any) */



static Text   evalModule  = 0;          /* Name of module we eval exprs in */
static String currProject = 0;          /* Name of current project file    */
static Bool   projectLoaded = FALSE;    /* TRUE => project file loaded     */

static Bool   autoMain   = FALSE;
static String lastEdit   = 0;           /* Name of script to edit (if any) */
static Int    lastEdLine = 0;           /* Editor line number (if possible)*/
static String prompt     = 0;           /* Prompt string                   */
static Int    hpSize     = DEFAULTHEAP; /* Desired heap size               */
       String hugsEdit   = 0;           /* String for editor command       */
       String hugsPath   = 0;           /* String for file search path     */

       List  ifaces_outstanding = NIL;

#if REDIRECT_OUTPUT
static Bool disableOutput = FALSE;      /* redirect output to buffer?      */
#endif

String bool2str ( Bool b )
{
   if (b) return "Yes"; else return "No ";
}

void ppSmStack ( String who )
{
   int i, j;
return;
   fflush(stdout);fflush(stderr);
   printf ( "\n" );
   printf ( "ppSmStack %s:  numScripts = %d   namesUpto = %d  needsImports = %s\n",
            who, numScripts, namesUpto, bool2str(needsImports) );
   assert (namesUpto >= numScripts);
   printf ( "     Det FrS Pst ObL           Module Ext   Size ModTime  Path\n" );
   for (i = namesUpto-1; i >= 0; i--) {
      printf ( "%c%2d: %3s %3s %3s %3s %16s %-4s %5ld %8lx %s\n",
               (i==numScripts ? '*' : ' '),
               i, bool2str(scriptInfo[i].details), 
                  bool2str(scriptInfo[i].fromSource),
                  bool2str(scriptInfo[i].postponed), 
                  bool2str(scriptInfo[i].objLoaded),
                  scriptInfo[i].modName, 
                  scriptInfo[i].fromSource ? scriptInfo[i].srcExt : "",
                  scriptInfo[i].size, 
                  scriptInfo[i].lastChange,
                  scriptInfo[i].path
             );
   }
   fflush(stdout);fflush(stderr);
   ppScripts();
   ppModules();
   printf ( "\n" );
}

/* --------------------------------------------------------------------------
 * Hugs entry point:
 * ------------------------------------------------------------------------*/

#ifndef NO_MAIN /* we omit main when building the "Hugs server" */
 
Main main ( Int, String [] );       /* now every func has a prototype  */

Main main(argc,argv)
int  argc;
char *argv[]; {
#ifdef HAVE_CONSOLE_H /* Macintosh port */
    _ftype = 'TEXT';
    _fcreator = 'R*ch';       /*  // 'KAHL';      //'*TEX';       //'ttxt'; */

    console_options.top = 50;
    console_options.left = 20;

    console_options.nrows = 32;
    console_options.ncols = 80;

    console_options.pause_atexit = 1;
    console_options.title = "\pHugs";

    console_options.procID = 5;
    argc = ccommand(&argv);
#endif

    CStackBase = &argc;                 /* Save stack base for use in gc   */

    /* If first arg is +Q or -Q, be entirely silent, and automatically run
       main after loading scripts.  Useful for running the nofib suite.    */
    if (argc > 1 && (strcmp(argv[1],"+Q") == 0 || strcmp(argv[1],"-Q")==0)) {
       autoMain = TRUE;
       if (strcmp(argv[1],"-Q") == 0) {
	 hugsEnableOutput(0);
       }
    }

    Printf("__   __ __  __  ____   ___      _________________________________________\n");
    Printf("||   || ||  || ||  || ||__      STGHugs: Based on the Haskell 98 standard\n");
    Printf("||___|| ||__|| ||__||  __||     Copyright (c) 1994-1999\n");
    Printf("||---||         ___||           World Wide Web: http://haskell.org/hugs\n");
    Printf("||   ||                         Report bugs to: hugs-bugs@haskell.org\n");
    Printf("||   || Version: %s _________________________________________\n\n",HUGS_VERSION);

    /* Get the absolute path to the directory containing the hugs 
       executable, so that we know where the Prelude and nHandle.so/.dll are.
       We do this by reading env var STGHUGSDIR.  This needs to succeed, so
       setInstallDir won't return unless it succeeds.
    */
    setInstallDir ( argv[0] );

#if SYMANTEC_C
    Printf("   Ported to Macintosh by Hans Aberg, compiled " __DATE__ ".\n\n");
#endif
    FlushStdout();
    interpreter(argc,argv);
    Printf("[Leaving Hugs]\n");
    everybody(EXIT);
    shutdownHaskell();
    FlushStdout();
    fflush(stderr);
    exit(0);
    MainDone();
}

#endif

/* --------------------------------------------------------------------------
 * Initialization, interpret command line args and read prelude:
 * ------------------------------------------------------------------------*/

static Void local initialize(argc,argv)/* Interpreter initialization       */
Int    argc;
String argv[]; {
    Script i;
    String proj        = 0;
    char argv_0_orig[1000];

    setLastEdit((String)0,0);
    lastEdit      = 0;
    scriptFile    = 0;
    numScripts    = 0;
    namesUpto     = 1;

#if HUGS_FOR_WINDOWS
    hugsEdit      = strCopy(fromEnv("EDITOR","c:\\windows\\notepad.exe"));
#elif SYMANTEC_C
    hugsEdit      = "";
#else
    hugsEdit      = strCopy(fromEnv("EDITOR",NULL));
#endif
    hugsPath      = strCopy(HUGSPATH);
    readOptions("-p\"%s> \" -r$$");
#if USE_REGISTRY
    projectPath   = strCopy(readRegChildStrings(HKEY_LOCAL_MACHINE,ProjectRoot,
                                                "HUGSPATH", PATHSEP, ""));
    readOptions(readRegString(HKEY_LOCAL_MACHINE,HugsRoot,"Options",""));
    readOptions(readRegString(HKEY_CURRENT_USER, HugsRoot,"Options",""));
#endif /* USE_REGISTRY */
    readOptions(fromEnv("STGHUGSFLAGS",""));

   strncpy(argv_0_orig,argv[0],1000);   /* startupHaskell mangles argv[0] */
   startupHaskell (argc,argv);
   argc = prog_argc; argv = prog_argv;

   namesUpto = numScripts = 0;

   /* Pre-scan flags to see if -c or +c is present.  This needs to
      precede adding the stack entry for Prelude.  On the other hand,
      that stack entry needs to be made before the cmd line args are
      properly examined.  Hence the following pre-scan of them.
   */
   for (i=1; i < argc; ++i) {
      if (strcmp(argv[i], "--")==0) break;
      if (strcmp(argv[i], "-c")==0) combined = FALSE;
      if (strcmp(argv[i], "+c")==0) combined = TRUE;
   }

   addStackEntry("Prelude");
   if (combined) addStackEntry("PrelHugs");

   for (i=1; i < argc; ++i) {            /* process command line arguments  */
        if (strcmp(argv[i], "--")==0) break;
        if (strcmp(argv[i],"+")==0 && i+1<argc) {
            if (proj) {
                ERRMSG(0) "Multiple project filenames on command line"
                EEND;
            } else {
                proj = argv[++i];
            }
        } else if (argv[i] && argv[i][0]/* workaround for /bin/sh silliness*/
                 && !processOption(argv[i])) {
            addStackEntry(argv[i]);
        }
    }

#if DEBUG
    { 
       char exe_name[N_INSTALLDIR + 6];
       strcpy(exe_name, installDir);
       strcat(exe_name, "hugs");
       DEBUG_LoadSymbols(exe_name);
    }
#endif


#if 0
    if (!scriptName[0]) {
        Printf("Prelude not found on current path: \"%s\"\n",
               hugsPath ? hugsPath : "");
        fatal("Unable to load prelude");
    }
#endif

    if (haskell98) {
        Printf("Haskell 98 mode: Restart with command line option -98 to enable extensions\n");
    } else {
        Printf("Hugs mode: Restart with command line option +98 for Haskell 98 mode\n");
    }

    if (combined) {
        Printf("Combined mode: Restart with command line -c for standalone mode\n\n" );
    } else {
        Printf("Standalone mode: Restart with command line +c for combined mode\n\n" );
    }
 
    everybody(PREPREL);

    evalModule = findText("");      /* evaluate wrt last module by default */
    if (proj) {
        if (namesUpto>1) {
            fprintf(stderr,
                    "\nUsing project file, ignoring additional filenames\n");
        }
        loadProject(strCopy(proj));
    }
    readScripts(0);
}

/* --------------------------------------------------------------------------
 * Command line options:
 * ------------------------------------------------------------------------*/

struct options {                        /* command line option toggles     */
    char   c;                           /* table defined in main app.      */
    int    h98;
    String description;
    Bool   *flag;
};
extern struct options toggle[];

static Void local toggleSet(c,state)    /* Set command line toggle         */
Char c;
Bool state; {
    Int i;
    for (i=0; toggle[i].c; ++i)
        if (toggle[i].c == c) {
            *toggle[i].flag = state;
            return;
        }
    ERRMSG(0) "Unknown toggle `%c'", c
    EEND;
}

static Void local togglesIn(state)      /* Print current list of toggles in*/
Bool state; {                           /* given state                     */
    Int count = 0;
    Int i;
    for (i=0; toggle[i].c; ++i)
 	if (*toggle[i].flag == state && (!haskell98 || toggle[i].h98)) {
            if (count==0)
                Putchar((char)(state ? '+' : '-'));
            Putchar(toggle[i].c);
            count++;
        }
    if (count>0)
        Putchar(' ');
}

static Void local optionInfo() {        /* Print information about command */
    static String fmts = "%-5s%s\n";    /* line settings                   */
    static String fmtc = "%-5c%s\n";
    Int    i;

    Printf("TOGGLES: groups begin with +/- to turn options on/off resp.\n");
    for (i=0; toggle[i].c; ++i) {
	if (!haskell98 || toggle[i].h98) {
  	    Printf(fmtc,toggle[i].c,toggle[i].description);
	}
    }

    Printf("\nOTHER OPTIONS: (leading + or - makes no difference)\n");
    Printf(fmts,"hnum","Set heap size (cannot be changed within Hugs)");
    Printf(fmts,"pstr","Set prompt string to str");
    Printf(fmts,"rstr","Set repeat last expression string to str");
    Printf(fmts,"Pstr","Set search path for modules to str");
    Printf(fmts,"Estr","Use editor setting given by str");
    Printf(fmts,"cnum","Set constraint cutoff limit");
#if USE_PREPROCESSOR  && (defined(HAVE_POPEN) || defined(HAVE__POPEN))
    Printf(fmts,"Fstr","Set preprocessor filter to str");
#endif

    Printf("\nCurrent settings: ");
    togglesIn(TRUE);
    togglesIn(FALSE);
    Printf("-h%d",heapSize);
    Printf(" -p");
    printString(prompt);
    Printf(" -r");
    printString(repeatStr);
    Printf(" -c%d",cutoff);
    Printf("\nSearch path     : -P");
    printString(hugsPath);
#if 0
ToDo
    if (projectPath!=NULL) {
        Printf("\nProject Path    : %s",projectPath);
    }
#endif
    Printf("\nEditor setting  : -E");
    printString(hugsEdit);
#if USE_PREPROCESSOR  && (defined(HAVE_POPEN) || defined(HAVE__POPEN))
    Printf("\nPreprocessor    : -F");
    printString(preprocessor);
#endif
    Printf("\nCompatibility   : %s", haskell98 ? "Haskell 98 (+98)"
 					       : "Hugs Extensions (-98)");
    Putchar('\n');
}

#if USE_REGISTRY || HUGS_FOR_WINDOWS
#define PUTC(c)                         \
    *next++=(c)

#define PUTS(s)                         \
    strcpy(next,s);                     \
    next+=strlen(next)

#define PUTInt(optc,i)                  \
    sprintf(next,"-%c%d",optc,i);       \
    next+=strlen(next)

#define PUTStr(c,s)                     \
    next=PUTStr_aux(next,c,s)

static String local PUTStr_aux ( String,Char, String));

static String local PUTStr_aux(next,c,s)
String next;
Char   c;
String s; {
    if (s) { 
        String t = 0;
        sprintf(next,"-%c\"",c); 
        next+=strlen(next);      
        for(t=s; *t; ++t) {
            PUTS(unlexChar(*t,'"'));
        }
        next+=strlen(next);      
        PUTS("\" ");
    }
    return next;
}

static String local optionsToStr() {          /* convert options to string */
    static char buffer[2000];
    String next = buffer;

    Int i;
    for (i=0; toggle[i].c; ++i) {
        PUTC(*toggle[i].flag ? '+' : '-');
        PUTC(toggle[i].c);
        PUTC(' ');
    }
    PUTS(haskell98 ? "+98 " : "-98 ");
    PUTInt('h',hpSize);  PUTC(' ');
    PUTStr('p',prompt);
    PUTStr('r',repeatStr);
    PUTStr('P',hugsPath);
    PUTStr('E',hugsEdit);
    PUTInt('c',cutoff);  PUTC(' ');
#if USE_PREPROCESSOR  && (defined(HAVE_POPEN) || defined(HAVE__POPEN))
    PUTStr('F',preprocessor);
#endif
    PUTC('\0');
    return buffer;
}
#endif /* USE_REGISTRY */

#undef PUTC
#undef PUTS
#undef PUTInt
#undef PUTStr

static Void local readOptions(options)         /* read options from string */
String options; {
    String s;
    if (options) {
        stringInput(options);
        while ((s=readFilename())!=0) {
            if (*s && !processOption(s)) {
                ERRMSG(0) "Option string must begin with `+' or `-'"
                EEND;
            }
        }
    }
}

static Bool local processOption(s)      /* process string s for options,   */
String s; {                             /* return FALSE if none found.     */
    Bool state;

    if (s[0]=='-')
        state = FALSE;
    else if (s[0]=='+')
        state = TRUE;
    else
        return FALSE;

    while (*++s)
        switch (*s) {
            case 'Q' : break;                           /* already handled */

            case 'p' : if (s[1]) {
                           if (prompt) free(prompt);
                           prompt = strCopy(s+1);
                       }
                       return TRUE;

            case 'r' : if (s[1]) {
                           if (repeatStr) free(repeatStr);
                           repeatStr = strCopy(s+1);
                       }
                       return TRUE;

            case 'P' : {
                           String p = substPath(s+1,hugsPath ? hugsPath : "");
                           if (hugsPath) free(hugsPath);
                           hugsPath = p;
                           return TRUE;
                       }

            case 'E' : if (hugsEdit) free(hugsEdit);
                       hugsEdit = strCopy(s+1);
                       return TRUE;

#if USE_PREPROCESSOR  && (defined(HAVE_POPEN) || defined(HAVE__POPEN))
            case 'F' : if (preprocessor) free(preprocessor);
                       preprocessor = strCopy(s+1);
                       return TRUE;
#endif

            case 'h' : setHeapSize(s+1);
                       return TRUE;

            case 'c' : if (heapBuilt()) {
                          FPrintf(stderr, 
                                  "You can't enable/disable combined"
                                  " operation inside Hugs\n" );
                       } else {
 		          /* don't do anything, since pre-scan of args
                             will have got it already */
                       }
                       return TRUE;

            case 'D' : /* hack */
                {
                    extern void setRtsFlags( int x );
                    setRtsFlags(argToInt(s+1));
                    return TRUE;
                }

            default  : if (strcmp("98",s)==0) {
                           if (heapBuilt() && ((state && !haskell98) ||
                                               (!state && haskell98))) {
                               FPrintf(stderr,
                                       "Haskell 98 compatibility cannot be changed"
                                       " while the interpreter is running\n");
                           } else {
                               haskell98 = state;
                           }
                           return TRUE;
                       } else {
                           toggleSet(*s,state);
                       }
                       break;
        }
    return TRUE;
}

static Void local setHeapSize(s) 
String s; {
    if (s) {
        hpSize = argToInt(s);
        if (hpSize < MINIMUMHEAP)
            hpSize = MINIMUMHEAP;
        else if (MAXIMUMHEAP && hpSize > MAXIMUMHEAP)
            hpSize = MAXIMUMHEAP;
        if (heapBuilt() && hpSize != heapSize) {
            /* ToDo: should this use a message box in winhugs? */
#if USE_REGISTRY
            FPrintf(stderr,"Change to heap size will not take effect until you rerun Hugs\n");
#else
            FPrintf(stderr,"You cannot change heap size from inside Hugs\n");
#endif
        } else {
            heapSize = hpSize;
        }
    }
}

static Int local argToInt(s)            /* read integer from argument str  */
String s; {
    Int    n = 0;
    String t = s;

    if (*s=='\0' || !isascii((int)(*s)) || !isdigit((int)(*s))) {
        ERRMSG(0) "Missing integer in option setting \"%s\"", t
        EEND;
    }

    do {
        Int d = (*s++) - '0';
        if (n > ((MAXPOSINT - d)/10)) {
            ERRMSG(0) "Option setting \"%s\" is too large", t
            EEND;
        }
        n     = 10*n + d;
    } while (isascii((int)(*s)) && isdigit((int)(*s)));

    if (*s=='K' || *s=='k') {
        if (n > (MAXPOSINT/1000)) {
            ERRMSG(0) "Option setting \"%s\" is too large", t
            EEND;
        }
        n *= 1000;
        s++;
    }

#if MAXPOSINT > 1000000                 /* waste of time on 16 bit systems */
    if (*s=='M' || *s=='m') {
        if (n > (MAXPOSINT/1000000)) {
            ERRMSG(0) "Option setting \"%s\" is too large", t
            EEND;
        }
        n *= 1000000;
        s++;
    }
#endif

#if MAXPOSINT > 1000000000
    if (*s=='G' || *s=='g') {
        if (n > (MAXPOSINT/1000000000)) {
            ERRMSG(0) "Option setting \"%s\" is too large", t
            EEND;
        }
        n *= 1000000000;
        s++;
    }
#endif

    if (*s!='\0') {
        ERRMSG(0) "Unwanted characters after option setting \"%s\"", t
        EEND;
    }

    return n;
}

/* --------------------------------------------------------------------------
 * Print Menu of list of commands:
 * ------------------------------------------------------------------------*/

static struct cmd cmds[] = {
 {":?",      HELP},   {":cd",   CHGDIR},  {":also",    ALSO},
 {":type",   TYPEOF}, {":!",    SYSTEM},  {":load",    LOAD},
 {":reload", RELOAD}, {":gc",   COLLECT}, {":edit",    EDIT},
 {":quit",   QUIT},   {":set",  SET},     {":find",    FIND},
 {":names",  NAMES},  {":info", INFO},    {":project", PROJECT},
 {":dump",   DUMP},   {":ztats", STATS},
 {":module",SETMODULE}, 
 {":browse", BROWSE},
#if EXPLAIN_INSTANCE_RESOLUTION
 {":xplain", XPLAIN},
#endif
 {":version", PNTVER},
 {"",      EVAL},
 {0,0}
};

static Void local menu() {
    Printf("LIST OF COMMANDS:  Any command may be abbreviated to :c where\n");
    Printf("c is the first character in the full name.\n\n");
    Printf(":load <filenames>   load modules from specified files\n");
    Printf(":load               clear all files except prelude\n");
    Printf(":also <filenames>   read additional modules\n");
    Printf(":reload             repeat last load command\n");
    Printf(":project <filename> use project file\n");
    Printf(":edit <filename>    edit file\n");
    Printf(":edit               edit last module\n");
    Printf(":module <module>    set module for evaluating expressions\n");
    Printf("<expr>              evaluate expression\n");
    Printf(":type <expr>        print type of expression\n");
    Printf(":?                  display this list of commands\n");
    Printf(":set <options>      set command line options\n");
    Printf(":set                help on command line options\n");
    Printf(":names [pat]        list names currently in scope\n");
    Printf(":info <names>       describe named objects\n");
    Printf(":browse <modules>   browse names defined in <modules>\n");
#if EXPLAIN_INSTANCE_RESOLUTION
    Printf(":xplain <context>   explain instance resolution for <context>\n");
#endif
    Printf(":find <name>        edit module containing definition of name\n");
    Printf(":!command           shell escape\n");
    Printf(":cd dir             change directory\n");
    Printf(":gc                 force garbage collection\n");
    Printf(":version            print Hugs version\n");
    Printf(":dump <name>        print STG code for named fn\n");
#ifdef CRUDE_PROFILING
    Printf(":ztats <name>       print reduction stats\n");
#endif
    Printf(":quit               exit Hugs interpreter\n");
}

static Void local guidance() {
    Printf("Command not recognised.  ");
    forHelp();
}

static Void local forHelp() {
    Printf("Type :? for help\n");
}

/* --------------------------------------------------------------------------
 * Setting of command line options:
 * ------------------------------------------------------------------------*/

struct options toggle[] = {             /* List of command line toggles    */
    {'s', 1, "Print no. reductions/cells after eval", &showStats},
    {'t', 1, "Print type after evaluation",           &addType},
    {'g', 1, "Print no. cells recovered after gc",    &gcMessages},
    {'l', 1, "Literate modules as default",           &literateScripts},
    {'e', 1, "Warn about errors in literate modules", &literateErrors},
    {'.', 1, "Print dots to show progress",           &useDots},
    {'q', 1, "Print nothing to show progress",        &quiet},
    {'w', 1, "Always show which modules are loaded",  &listScripts},
    {'k', 1, "Show kind errors in full",              &kindExpert},
    {'o', 0, "Allow overlapping instances",           &allowOverlap},
    {'S', 1, "Debug: show generated SC code",         &debugSC},
#if EXPLAIN_INSTANCE_RESOLUTION
    {'x', 1, "Explain instance resolution",           &showInstRes},
#endif
#if MULTI_INST
    {'m', 0, "Use multi instance resolution",         &multiInstRes},
#endif
    {0,   0, 0,                                       0}
};

static Void local set() {               /* change command line options from*/
    String s;                           /* Hugs command line               */

    if ((s=readFilename())!=0) {
        do {
            if (!processOption(s)) {
                ERRMSG(0) "Option string must begin with `+' or `-'"
                EEND;
            }
        } while ((s=readFilename())!=0);
#if USE_REGISTRY
        writeRegString("Options", optionsToStr());
#endif
    }
    else
        optionInfo();
}

/* --------------------------------------------------------------------------
 * Change directory command:
 * ------------------------------------------------------------------------*/

static Void local changeDir() {         /* change directory                */
    String s = readFilename();
    if (s && chdir(s)) {
        ERRMSG(0) "Unable to change to directory \"%s\"", s
        EEND;
    }
}

/* --------------------------------------------------------------------------
 * Loading project and script files:
 * ------------------------------------------------------------------------*/

static Void local loadProject(s)        /* Load project file               */
String s; {
    clearProject();
    currProject = s;
    projInput(currProject);
    scriptFile = currProject;
    forgetScriptsFrom(N_PRELUDE_SCRIPTS);
    while ((s=readFilename())!=0)
        addStackEntry(s);
    if (namesUpto<=1) {
        ERRMSG(0) "Empty project file"
        EEND;
    }
    scriptFile    = 0;
    projectLoaded = TRUE;
}

static Void local clearProject() {      /* clear name for current project  */
    if (currProject)
        free(currProject);
    currProject   = 0;
    projectLoaded = FALSE;
#if HUGS_FOR_WINDOWS
    setLastEdit((String)0,0);
#endif
}



static Void local makeStackEntry ( ScriptInfo* ent, String iname )
{
   Bool   ok, fromObj;
   Bool   sAvail, iAvail, oAvail;
   Time   sTime,  iTime,  oTime;
   Long   sSize,  iSize,  oSize;
   String path,   sExt;

   ok = findFilesForModule (
           iname,
           &path,
           &sExt,
           &sAvail, &sTime, &sSize,
           &iAvail, &iTime, &iSize,
           &oAvail, &oTime, &oSize
        );
   if (!ok) {
      ERRMSG(0) 
         "Can't find source or object+interface for module \"%s\"",
         /* "Can't find source for module \"%s\"", */
         iname
      EEND;
   }
   /* findFilesForModule should enforce this */
   if (!(sAvail || (oAvail && iAvail))) 
      internal("chase");
   /* Load objects in preference to sources if both are available */
   /* 11 Oct 99: disable object loading in the interim.
      Will probably only reinstate when HEP becomes available.
   */
   if (combined) {
      fromObj = sAvail
                ? (oAvail && iAvail && timeEarlier(sTime,oTime))
                : TRUE;
   } else {
      fromObj = FALSE;
   }

   /* ToDo: namesUpto overflow */
   ent->modName     = strCopy(iname);
   ent->details     = TRUE;
   ent->path        = path;
   ent->fromSource  = !fromObj;
   ent->srcExt      = sExt;
   ent->postponed   = FALSE;
   ent->lastChange  = sTime; /* ToDo: is this right? */
   ent->size        = fromObj ? iSize : sSize;
   ent->oSize       = fromObj ? oSize : 0;
   ent->objLoaded   = FALSE;
}



static Void nukeEnding( String s )
{
    Int l = strlen(s);
    if (l > 4 && strncmp(s+l-4,".u_o" ,4)==0) s[l-4] = 0; else
    if (l > 5 && strncmp(s+l-5,".u_hi",5)==0) s[l-5] = 0; else
    if (l > 3 && strncmp(s+l-3,".hs"  ,3)==0) s[l-3] = 0; else
    if (l > 4 && strncmp(s+l-4,".lhs" ,4)==0) s[l-4] = 0; else
    if (l > 4 && strncmp(s+l-4,".dll" ,4)==0) s[l-4] = 0; else
    if (l > 4 && strncmp(s+l-4,".DLL" ,4)==0) s[l-4] = 0;
}

static Void local addStackEntry(s)     /* Add script to list of scripts    */
String s; {                            /* to be read in ...                */
    String s2;
    Bool   found;
    Int    i;

    if (namesUpto>=NUM_SCRIPTS) {
        ERRMSG(0) "Too many module files (maximum of %d allowed)",
                  NUM_SCRIPTS
        EEND;
    }

    s = strCopy(s);
    nukeEnding(s);
    for (s2 = s; *s2; s2++)
       if (*s2 == SLASH && *(s2+1)) s = s2+1;

    found = FALSE;
    for (i = 0; i < namesUpto; i++)
       if (strcmp(scriptInfo[i].modName,s)==0)
          found = TRUE;

    if (!found) {
       makeStackEntry ( &scriptInfo[namesUpto], strCopy(s) );
       namesUpto++;
    }
    free(s);
}

/* Return TRUE if no imports were needed; FALSE otherwise. */
static Bool local addScript(stacknum)   /* read single file                */
Int stacknum; {
   Bool didPrelude;
   static char name[FILENAME_MAX+1];
   Int len = scriptInfo[stacknum].size;

#if HUGS_FOR_WINDOWS                    /* Set clock cursor while loading  */
    allowBreak();
    SetCursor(LoadCursor(NULL, IDC_WAIT));
#endif

    //   setLastEdit(name,0);

   strcpy(name, scriptInfo[stacknum].path);
   strcat(name, scriptInfo[stacknum].modName);
   if (scriptInfo[stacknum].fromSource)
      strcat(name, scriptInfo[stacknum].srcExt); else
      strcat(name, ".u_hi");

   scriptFile = name;

   if (scriptInfo[stacknum].fromSource) {
      if (lastWasObject) {
         didPrelude = processInterfaces();
         if (didPrelude) {
            preludeLoaded = TRUE;
            everybody(POSTPREL);
         }
      }
      lastWasObject = FALSE;
      Printf("Reading script \"%s\":\n",name);
      needsImports = FALSE;
      parseScript(name,len);
      if (needsImports) return FALSE;
      checkDefns();
      typeCheckDefns();
      compileDefns();
   } else {
      Cell    iface;
      List    imports;
      ZTriple iface_info;
      char    nameObj[FILENAME_MAX+1];
      Int     sizeObj;

      Printf("Reading  iface \"%s\":\n", name);
      scriptFile = name;
      needsImports = FALSE;

      // set nameObj for the benefit of openGHCIface
      strcpy(nameObj, scriptInfo[stacknum].path);
      strcat(nameObj, scriptInfo[stacknum].modName);
      strcat(nameObj, DLL_ENDING);
      sizeObj = scriptInfo[stacknum].oSize;

      iface = readInterface(name,len);
      imports = zsnd(iface); iface = zfst(iface);

      if (nonNull(imports)) chase(imports);
      scriptFile = 0;
      lastWasObject = TRUE;

      iface_info = ztriple(iface, findText(nameObj), mkInt(sizeObj) );
      ifaces_outstanding = cons(iface_info,ifaces_outstanding);

      if (needsImports) return FALSE;
   }
 
   scriptFile = 0;

   return TRUE;
}


Bool chase(imps)                        /* Process list of import requests */
List imps; {
    Int    dstPosn;
    ScriptInfo tmp;
    Int    origPos  = numScripts;       /* keep track of original position */
    String origName = scriptInfo[origPos].modName;
    for (; nonNull(imps); imps=tl(imps)) {
        String iname = textToStr(textOf(hd(imps)));
        Int    i     = 0;
        for (; i<namesUpto; i++)
            if (strcmp(scriptInfo[i].modName,iname)==0)
                break;
	//fprintf(stderr, "import name = %s   num = %d\n", iname, i );

        if (i<namesUpto) {
           /* We should have filled in the details of each module
              the first time we hear about it.
	   */
           assert(scriptInfo[i].details);
        }

        if (i>=origPos) {               /* Neither loaded or queued        */
            String theName;
            Time   theTime;
            Bool   thePost;
            Bool   theFS;

            needsImports = TRUE;
            if (scriptInfo[origPos].fromSource)
               scriptInfo[origPos].postponed  = TRUE;

            if (i==namesUpto) {         /* Name not found (i==namesUpto)   */
                 /* Find out where it lives, whether source or object, etc */
               makeStackEntry ( &scriptInfo[i], iname );
               namesUpto++;
            }
            else 
            if (scriptInfo[i].postponed && scriptInfo[i].fromSource) {
                                        /* Check for recursive dependency  */
                ERRMSG(0)
                  "Recursive import dependency between \"%s\" and \"%s\"",
                  scriptInfo[origPos].modName, iname
                EEND;
            }
            /* Move stack entry i to somewhere below origPos.  If i denotes 
             * an object, destination is immediately below origPos.  
             * Otherwise, it's underneath the queue of objects below origPos.
             */
            dstPosn = origPos-1;
            if (scriptInfo[i].fromSource)
               while (!scriptInfo[dstPosn].fromSource && dstPosn > 0)
                  dstPosn--;

            dstPosn++;
            tmp = scriptInfo[i];
            for (; i > dstPosn; i--) scriptInfo[i] = scriptInfo[i-1];
            scriptInfo[dstPosn] = tmp;
            if (dstPosn < nextNumScripts) nextNumScripts = dstPosn;
            origPos++;
        }
    }
    return needsImports;
}

static Void local forgetScriptsFrom(scno)/* remove scripts from system     */
Script scno; {
    Script i;
#if 0
    for (i=scno; i<namesUpto; ++i)
        if (scriptName[i])
            free(scriptName[i]);
#endif
    dropScriptsFrom(scno-1);
    namesUpto = scno;
    if (numScripts>namesUpto)
        numScripts = scno;
}

/* --------------------------------------------------------------------------
 * Commands for loading and removing script files:
 * ------------------------------------------------------------------------*/

static Void local load() {           /* read filenames from command line   */
    String s;                        /* and add to list of scripts waiting */
                                     /* to be read                         */
    while ((s=readFilename())!=0)
        addStackEntry(s);
    readScripts(N_PRELUDE_SCRIPTS);
}

static Void local project() {          /* read list of script names from   */
    String s;                          /* project file                     */

    if ((s=readFilename()) || currProject) {
        if (!s)
            s = strCopy(currProject);
        else if (readFilename()) {
            ERRMSG(0) "Too many project files"
            EEND;
        }
        else
            s = strCopy(s);
    }
    else {
        ERRMSG(0) "No project filename specified"
        EEND;
    }
    loadProject(s);
    readScripts(N_PRELUDE_SCRIPTS);
}

static Void local readScripts(n)        /* Reread current list of scripts, */
Int n; {                                /* loading everything after and    */
    Time timeStamp;                     /* including the first script which*/
    Long fileSize;                      /* has been either changed or added*/
    static char name[FILENAME_MAX+1];
    Bool didPrelude;

    lastWasObject = FALSE;
    ppSmStack("readscripts-begin");
#if HUGS_FOR_WINDOWS
    SetCursor(LoadCursor(NULL, IDC_WAIT));
#endif

#if 0
    for (; n<numScripts; n++) {         /* Scan previously loaded scripts  */
        ppSmStack("readscripts-loop1");
        getFileInfo(scriptName[n], &timeStamp, &fileSize);
        if (timeChanged(timeStamp,lastChange[n])) {
            dropScriptsFrom(n-1);
            numScripts = n;
            break;
        }
    }
    for (; n<NUM_SCRIPTS; n++)          /* No scripts have been postponed  */
        postponed[n] = FALSE;           /* at this stage                   */
    numScripts = 0;

    while (numScripts<namesUpto) {      /* Process any remaining scripts   */
        ppSmStack("readscripts-loop2");
        getFileInfo(scriptName[numScripts], &timeStamp, &fileSize);
        timeSet(lastChange[numScripts],timeStamp);
        if (numScripts>0)               /* no new script for prelude       */
            startNewScript(scriptName[numScripts]);
        if (addScript(scriptName[numScripts],fileSize))
            numScripts++;
        else
            dropScriptsFrom(numScripts-1);
    }
#endif

    interface(RESET);

    for (; n<numScripts; n++) {
        ppSmStack("readscripts-loop2");
        strcpy(name, scriptInfo[n].path);
        strcat(name, scriptInfo[n].modName);
        if (scriptInfo[n].fromSource)
           strcat(name, scriptInfo[n].srcExt); else
           strcat(name, ".u_hi");  //ToDo: should be .o
        getFileInfo(name,&timeStamp, &fileSize);
        if (timeChanged(timeStamp,scriptInfo[n].lastChange)) {
           dropScriptsFrom(n-1);
           numScripts = n;
           break;
        }
    }
    for (; n<NUM_SCRIPTS; n++)
        scriptInfo[n].postponed = FALSE;

    //numScripts = 0;

    while (numScripts < namesUpto) {
       ppSmStack ( "readscripts-loop2" );

       if (scriptInfo[numScripts].fromSource) {

          if (numScripts>0)
              startNewScript(scriptInfo[numScripts].modName);
          nextNumScripts = NUM_SCRIPTS; //bogus initialisation
          if (addScript(numScripts)) {
             numScripts++;
             assert(nextNumScripts==NUM_SCRIPTS);
          }
          else
             dropScriptsFrom(numScripts-1);

       } else {
      
          if (scriptInfo[numScripts].objLoaded) {
             numScripts++;
          } else {
             scriptInfo[numScripts].objLoaded = TRUE;
             /* new */
             if (numScripts>0)
                 startNewScript(scriptInfo[numScripts].modName);
	     /* end */
             nextNumScripts = NUM_SCRIPTS;
             if (addScript(numScripts)) {
                numScripts++;
                assert(nextNumScripts==NUM_SCRIPTS);
             } else {
	        //while (!scriptInfo[numScripts].fromSource && numScripts > 0)
	        //   numScripts--;
	        //if (scriptInfo[numScripts].fromSource)
	        //   numScripts++;
                numScripts = nextNumScripts;
                assert(nextNumScripts<NUM_SCRIPTS);
             }
          }
       }
       if (numScripts==namesUpto) ppSmStack( "readscripts-final") ;
    }

    didPrelude = processInterfaces();
    if (didPrelude) {
       preludeLoaded = TRUE;
       everybody(POSTPREL);
    }


    { Int  m     = namesUpto-1;
      Text mtext = findText(scriptInfo[m].modName);

      /* Hack to avoid starting up in PrelHugs */
      if (mtext == findText("PrelHugs")) mtext = findText("Prelude");


      /* Commented out till we understand what
       * this is trying to do.
       * Problem, you cant find a module till later.
       */
#if 0
       setCurrModule(findModule(mtext)); 
#endif
      evalModule = mtext;
    }

    

    if (listScripts)
        whatScripts();
    if (numScripts<=1)
        setLastEdit((String)0, 0);
    ppSmStack("readscripts-end  ");
}

static Void local whatScripts() {       /* list scripts in current session */
    int i;
    Printf("\nHugs session for:");
    if (projectLoaded)
        Printf(" (project: %s)",currProject);
    for (i=0; i<numScripts; ++i)
      Printf("\n%s%s",scriptInfo[i].path, scriptInfo[i].modName);
    Putchar('\n');
}

/* --------------------------------------------------------------------------
 * Access to external editor:
 * ------------------------------------------------------------------------*/

static Void local editor() {            /* interpreter-editor interface    */
    String newFile  = readFilename();
    if (newFile) {
        setLastEdit(newFile,0);
        if (readFilename()) {
            ERRMSG(0) "Multiple filenames not permitted"
            EEND;
        }
    }
    runEditor();
}

static Void local find() {              /* edit file containing definition */
#if 0
This just plain wont work no more.
ToDo: Fix!
    String nm = readFilename();         /* of specified name               */
    if (!nm) {
        ERRMSG(0) "No name specified"
        EEND;
    }
    else if (readFilename()) {
        ERRMSG(0) "Multiple names not permitted"
        EEND;
    }
    else {
        Text t;
        Cell c;
        setCurrModule(findEvalModule());
        startNewScript(0);
        if (nonNull(c=findTycon(t=findText(nm)))) {
            if (startEdit(tycon(c).line,scriptName[scriptThisTycon(c)])) {
                readScripts(N_PRELUDE_SCRIPTS);
            }
        } else if (nonNull(c=findName(t))) {
            if (startEdit(name(c).line,scriptName[scriptThisName(c)])) {
                readScripts(N_PRELUDE_SCRIPTS);
            }
        } else {
            ERRMSG(0) "No current definition for name \"%s\"", nm
            EEND;
        }
    }
#endif
}

static Void local runEditor() {         /* run editor on script lastEdit   */
    if (startEdit(lastEdLine,lastEdit)) /* at line lastEdLine              */
        readScripts(N_PRELUDE_SCRIPTS);
}

static Void local setLastEdit(fname,line)/* keep name of last file to edit */
String fname;
Int    line; {
    if (lastEdit)
        free(lastEdit);
    lastEdit = strCopy(fname);
    lastEdLine = line;
#if HUGS_FOR_WINDOWS
    DrawStatusLine(hWndMain);           /* Redo status line                */
#endif
}

/* --------------------------------------------------------------------------
 * Read and evaluate an expression:
 * ------------------------------------------------------------------------*/

static Void local setModule(){/*set module in which to evaluate expressions*/
    String s = readFilename();
    if (!s) s = "";              /* :m clears the current module selection */
    evalModule = findText(s);
    setLastEdit(fileOfModule(findEvalModule()),0);
}

static Module local findEvalModule() { /*Module in which to eval expressions*/
    Module m = findModule(evalModule); 
    if (isNull(m))
        m = lastModule();
    return m;
}

static Void local evaluator() {        /* evaluate expr and print value    */
    Type  type, bd;
    Kinds ks   = NIL;

    setCurrModule(findEvalModule());
    scriptFile = 0;
    startNewScript(0);                 /* Enables recovery of storage      */
                                       /* allocated during evaluation      */
    parseExp();
    checkExp();
    defaultDefns = combined ? stdDefaults : evalDefaults;
    type         = typeCheckExp(TRUE);

    if (isPolyType(type)) {
        ks = polySigOf(type);
        bd = monotypeOf(type);
    }
    else
        bd = type;

    if (whatIs(bd)==QUAL) {
        ERRMSG(0) "Unresolved overloading" ETHEN
        ERRTEXT   "\n*** Type       : "    ETHEN ERRTYPE(type);
        ERRTEXT   "\n*** Expression : "    ETHEN ERREXPR(inputExpr);
        ERRTEXT   "\n"
        EEND;
    }
  
#ifdef WANT_TIMER
    updateTimers();
#endif

#if 1
    if (isProgType(ks,bd)) {
        inputExpr = ap(nameRunIO_toplevel,inputExpr);
        evalExp();
        Putchar('\n');
    } else {
        Cell d = provePred(ks,NIL,ap(classShow,bd));
        if (isNull(d)) {
            ERRMSG(0) "Cannot find \"show\" function for:" ETHEN
            ERRTEXT   "\n*** expression : "   ETHEN ERREXPR(inputExpr);
            ERRTEXT   "\n*** of type    : "   ETHEN ERRTYPE(type);
            ERRTEXT   "\n"
            EEND;
        }
        inputExpr = ap2(nameShow,           d,inputExpr);
        inputExpr = ap (namePutStr,         inputExpr);
        inputExpr = ap (nameRunIO_toplevel, inputExpr);

        evalExp(); printf("\n");
        if (addType) {
            printf(" :: ");
            printType(stdout,type);
            Putchar('\n');
        }
    }

#else

   printf ( "result type is " );
   printType ( stdout, type );
   printf ( "\n" );
   evalExp();
   printf ( "\n" );

#endif

}

static Void local stopAnyPrinting() {  /* terminate printing of expression,*/
    if (printing) {                    /* after successful termination or  */
        printing = FALSE;              /* runtime error (e.g. interrupt)   */
        Putchar('\n');
        if (showStats) {
#define plural(v)   v, (v==1?"":"s")
            Printf("%lu cell%s",plural(numCells));
            if (numGcs>0)
                Printf(", %u garbage collection%s",plural(numGcs));
            Printf(")\n");
#undef plural
        }
        FlushStdout();
        garbageCollect();
    }
}

/* --------------------------------------------------------------------------
 * Print type of input expression:
 * ------------------------------------------------------------------------*/

static Void local showtype() {         /* print type of expression (if any)*/
    Cell type;

    setCurrModule(findEvalModule());
    startNewScript(0);                 /* Enables recovery of storage      */
                                       /* allocated during evaluation      */
    parseExp();
    checkExp();
    defaultDefns = evalDefaults;
    type = typeCheckExp(FALSE);
    printExp(stdout,inputExpr);
    Printf(" :: ");
    printType(stdout,type);
    Putchar('\n');
}


static Void local browseit(mod,t,all)
Module mod; 
String t;
Bool all; {
    if (nonNull(mod)) {
	Cell cs;
	if (nonNull(t))
	    Printf("module %s where\n",textToStr(module(mod).text));
	for (cs = module(mod).names; nonNull(cs); cs=tl(cs)) {
	    Name nm = hd(cs);
	    /* only look at things defined in this module,
 	       unless `all' flag is set */
	    if (all || name(nm).mod == mod) {
		/* unwanted artifacts, like lambda lifted values,
		   are in the list of names, but have no types */
		if (nonNull(name(nm).type)) {
		    printExp(stdout,nm);
		    Printf(" :: ");
		    printType(stdout,name(nm).type);
		    if (isCfun(nm)) {
			Printf("  -- data constructor");
		    } else if (isMfun(nm)) {
			Printf("  -- class member");
		    } else if (isSfun(nm)) {
			Printf("  -- selector function");
		    }
		    Printf("\n");
		}
	    }
	}
    } else {
      if (isNull(mod)) {
	Printf("Unknown module %s\n",t);
      }
    }
}

static Void local browse() {            /* browse modules                  */
    Int    count = 0;                   /* or give menu of commands        */
    String s;
    Bool all = FALSE;

    setCurrModule(findEvalModule());
    startNewScript(0);                  /* for recovery of storage         */
    for (; (s=readFilename())!=0; count++)
	if (strcmp(s,"all") == 0) {
	    all = TRUE;
	    --count;
	} else
	    browseit(findModule(findText(s)),s,all);
    if (count == 0) {
	browseit(findEvalModule(),NULL,all);
    }
}

#if EXPLAIN_INSTANCE_RESOLUTION
static Void local xplain() {         /* print type of expression (if any)*/
    Cell d;
    Bool sir = showInstRes;

    setCurrModule(findEvalModule());
    startNewScript(0);                 /* Enables recovery of storage      */
				       /* allocated during evaluation      */
    parseContext();
    checkContext();
    showInstRes = TRUE;
    d = provePred(NIL,NIL,hd(inputContext));
    if (isNull(d)) {
	fprintf(stdout, "not Sat\n");
    } else {
	fprintf(stdout, "Sat\n");
    }
    showInstRes = sir;
}
#endif

/* --------------------------------------------------------------------------
 * Enhanced help system:  print current list of scripts or give information
 * about an object.
 * ------------------------------------------------------------------------*/

static String local objToStr(m,c)
Module m;
Cell   c; {
#if 1 || DISPLAY_QUANTIFIERS
    static char newVar[60];
    switch (whatIs(c)) {
        case NAME  : if (m == name(c).mod) {
                         sprintf(newVar,"%s", textToStr(name(c).text));
                     } else {
                         sprintf(newVar,"%s.%s",
                                        textToStr(module(name(c).mod).text),
                                        textToStr(name(c).text));
                     }
                     break;

        case TYCON : if (m == tycon(c).mod) {
                         sprintf(newVar,"%s", textToStr(tycon(c).text));
                     } else {
                         sprintf(newVar,"%s.%s",
                                        textToStr(module(tycon(c).mod).text),
                                        textToStr(tycon(c).text));
                     }
                     break;

        case CLASS : if (m == cclass(c).mod) {
                         sprintf(newVar,"%s", textToStr(cclass(c).text));
                     } else {
                         sprintf(newVar,"%s.%s",
                                        textToStr(module(cclass(c).mod).text),
                                        textToStr(cclass(c).text));
                     }
                     break;

        default    : internal("objToStr");
    }
    return newVar;
#else
    static char newVar[33];
    switch (whatIs(c)) {
        case NAME  : sprintf(newVar,"%s", textToStr(name(c).text));
                     break;

        case TYCON : sprintf(newVar,"%s", textToStr(tycon(c).text));
                     break;

        case CLASS : sprintf(newVar,"%s", textToStr(cclass(c).text));
                     break;

        default    : internal("objToStr");
    }
    return newVar;
#endif
}

extern Name nameHw;

static Void dumpStg ( void )
{
   String s;
   Int i;
   setCurrModule(findEvalModule());
   startNewScript(0);
   s = readFilename();

   /* request to locate a symbol by name */
   if (s && (*s == '?')) {
      Text t = findText(s+1);
      locateSymbolByName(t);
      return;
   }

   /* request to dump a bit of the heap */
   if (s && (*s == '-' || isdigit(*s))) {
      int i = atoi(s);
      print(i,100);
      printf("\n");
      return;
   }

   /* request to dump a symbol table entry */
   if (!s 
       || !(*s == 't' || *s == 'n' || *s == 'c' || *s == 'i')
       || !isdigit(s[1])) {
      fprintf(stderr, ":d -- bad request `%s'\n", s );
      return;
   }
   i = atoi(s+1);
   switch (*s) {
      case 't': dumpTycon(i); break;
      case 'n': dumpName(i); break;
      case 'c': dumpClass(i); break;
      case 'i': dumpInst(i); break;
      default: fprintf(stderr, ":d -- `%c' not implemented\n", *s );
   }
}


#if 0
static Void local dumpStg( void ) {       /* print STG stuff                 */
    String s;
    Text   t;
    Name   n;
    Int    i;
    Cell   v;                           /* really StgVar */
    setCurrModule(findEvalModule());
    startNewScript(0);
    for (; (s=readFilename())!=0;) {
        t = findText(s);
        v = n = NIL;
        /* find the name while ignoring module scopes */
        for (i=NAMEMIN; i<nameHw; i++)
           if (name(i).text == t) n = i;

        /* perhaps it's an "idNNNNNN" thing? */
        if (isNull(n) &&
            strlen(s) >= 3 && 
            s[0]=='i' && s[1]=='d' && isdigit(s[2])) {
           v = 0;
           i = 2;
           while (isdigit(s[i])) {
              v = v * 10 + (s[i]-'0');
              i++;
           }
           v = -v;
           n = nameFromStgVar(v);
        }

        if (isNull(n) && whatIs(v)==STGVAR) {
           Printf ( "\n{- `%s' has no nametable entry -}\n", s );
           printStg(stderr, v );
        } else
        if (isNull(n)) {
           Printf ( "Unknown reference `%s'\n", s );
        } else
	if (!isName(n)) {
           Printf ( "Not a Name: `%s'\n", s );
        } else
        if (isNull(name(n).stgVar)) {
           Printf ( "Doesn't have a STG tree: %s\n", s );
        } else {
           Printf ( "\n{- stgVar of `%s' is id%d -}\n", s, -name(n).stgVar);
           printStg(stderr, name(n).stgVar);
        }
    }
}
#endif

static Void local info() {              /* describe objects                */
    Int    count = 0;                   /* or give menu of commands        */
    String s;

    setCurrModule(findEvalModule());
    startNewScript(0);                  /* for recovery of storage         */
    for (; (s=readFilename())!=0; count++) {
        describe(findText(s));
    }
    if (count == 0) {
        whatScripts();
    }
}


static Void local describe(t)           /* describe an object              */
Text t; {
    Tycon  tc  = findTycon(t);
    Class  cl  = findClass(t);
    Name   nm  = findName(t);

    if (nonNull(tc)) {                  /* as a type constructor           */
        Type t = tc;
        Int  i;
        Inst in;
        for (i=0; i<tycon(tc).arity; ++i) {
            t = ap(t,mkOffset(i));
        }
        Printf("-- type constructor");
        if (kindExpert) {
            Printf(" with kind ");
            printKind(stdout,tycon(tc).kind);
        }
        Putchar('\n');
        switch (tycon(tc).what) {
            case SYNONYM      : Printf("type ");
                                printType(stdout,t);
                                Printf(" = ");
                                printType(stdout,tycon(tc).defn);
                                break;

            case NEWTYPE      :
            case DATATYPE     : {   List cs = tycon(tc).defn;
                                    if (tycon(tc).what==DATATYPE) {
                                        Printf("data ");
                                    } else {
                                        Printf("newtype ");
                                    }
                                    printType(stdout,t);
                                    Putchar('\n');
                                    mapProc(printSyntax,cs);
                                    if (hasCfun(cs)) {
                                        Printf("\n-- constructors:");
                                    }
                                    for (; hasCfun(cs); cs=tl(cs)) {
                                        Putchar('\n');
                                        printExp(stdout,hd(cs));
                                        Printf(" :: ");
                                        printType(stdout,name(hd(cs)).type);
                                    }
                                    if (nonNull(cs)) {
                                        Printf("\n-- selectors:");
                                    }
                                    for (; nonNull(cs); cs=tl(cs)) {
                                        Putchar('\n');
                                        printExp(stdout,hd(cs));
                                        Printf(" :: ");
                                        printType(stdout,name(hd(cs)).type);
                                    }
                                }
                                break;

            case RESTRICTSYN  : Printf("type ");
                                printType(stdout,t);
                                Printf(" = <restricted>");
                                break;
        }
        Putchar('\n');
        if (nonNull(in=findFirstInst(tc))) {
            Printf("\n-- instances:\n");
            do {
                showInst(in);
                in = findNextInst(tc,in);
            } while (nonNull(in));
        }
        Putchar('\n');
    }

    if (nonNull(cl)) {                  /* as a class                      */
        List  ins = cclass(cl).instances;
        Kinds ks  = cclass(cl).kinds;
        if (nonNull(ks) && isNull(tl(ks)) && hd(ks)==STAR) {
            Printf("-- type class");
        } else {
            Printf("-- constructor class");
            if (kindExpert) {
                Printf(" with arity ");
                printKinds(stdout,ks);
            }
        }
        Putchar('\n');
        mapProc(printSyntax,cclass(cl).members);
        Printf("class ");
        if (nonNull(cclass(cl).supers)) {
            printContext(stdout,cclass(cl).supers);
            Printf(" => ");
        }
        printPred(stdout,cclass(cl).head);

	if (nonNull(cclass(cl).fds)) {
	    List   fds = cclass(cl).fds;
	    String pre = " | ";
	    for (; nonNull(fds); fds=tl(fds)) {
		Printf(pre);
		printFD(stdout,hd(fds));
		pre = ", ";
	    }
	}

        if (nonNull(cclass(cl).members)) {
            List ms = cclass(cl).members;
            Printf(" where");
            do {
		Type t = name(hd(ms)).type;
                if (isPolyType(t)) {
		    t = monotypeOf(t);
		}
                Printf("\n  ");
                printExp(stdout,hd(ms));
                Printf(" :: ");
                if (isNull(tl(fst(snd(t))))) {
                    t = snd(snd(t));
                } else {
                    t = ap(QUAL,pair(tl(fst(snd(t))),snd(snd(t))));
                }
                printType(stdout,t);
                ms = tl(ms);
            } while (nonNull(ms));
        }
        Putchar('\n');
        if (nonNull(ins)) {
            Printf("\n-- instances:\n");
            do {
                showInst(hd(ins));
                ins = tl(ins);
            } while (nonNull(ins));
        }
        Putchar('\n');
    }

    if (nonNull(nm)) {                  /* as a function/name              */
        printSyntax(nm);
        printExp(stdout,nm);
        Printf(" :: ");
        if (nonNull(name(nm).type)) {
            printType(stdout,name(nm).type);
        } else {
            Printf("<unknown type>");
        }
        if (isCfun(nm)) {
            Printf("  -- data constructor");
        } else if (isMfun(nm)) {
            Printf("  -- class member");
        } else if (isSfun(nm)) {
            Printf("  -- selector function");
        }
        Printf("\n\n");
    }


    if (isNull(tc) && isNull(cl) && isNull(nm)) {
        Printf("Unknown reference `%s'\n",textToStr(t));
    }
}

static Void local printSyntax(nm)
Name nm; {
    Syntax sy = syntaxOf(nm);
    Text   t  = name(nm).text;
    String s  = textToStr(t);
    if (sy != defaultSyntax(t)) {
        Printf("infix");
        switch (assocOf(sy)) {
            case LEFT_ASS  : Putchar('l'); break;
            case RIGHT_ASS : Putchar('r'); break;
            case NON_ASS   : break;
        }
        Printf(" %i ",precOf(sy));
        if (isascii((int)(*s)) && isalpha((int)(*s))) {
            Printf("`%s`",s);
        } else {
            Printf("%s",s);
        }
        Putchar('\n');
    }
}

static Void local showInst(in)          /* Display instance decl header    */
Inst in; {
    Printf("instance ");
    if (nonNull(inst(in).specifics)) {
        printContext(stdout,inst(in).specifics);
        Printf(" => ");
    }
    printPred(stdout,inst(in).head);
    Putchar('\n');
}

/* --------------------------------------------------------------------------
 * List all names currently in scope:
 * ------------------------------------------------------------------------*/

static Void local listNames() {         /* list names matching optional pat*/
    String pat   = readFilename();
    List   names = NIL;
    Int    width = getTerminalWidth() - 1;
    Int    count = 0;
    Int    termPos;
    Module mod   = findEvalModule();

    if (pat) {                          /* First gather names to list      */
        do {
            names = addNamesMatching(pat,names);
        } while ((pat=readFilename())!=0);
    } else {
        names = addNamesMatching((String)0,names);
    }
    if (isNull(names)) {                /* Then print them out             */
        ERRMSG(0) "No names selected"
        EEND;
    }
    for (termPos=0; nonNull(names); names=tl(names)) {
        String s = objToStr(mod,hd(names));
        Int    l = strlen(s);
        if (termPos+1+l>width) { 
            Putchar('\n');       
            termPos = 0;         
        } else if (termPos>0) {  
            Putchar(' ');        
            termPos++;           
        }
        Printf("%s",s);
        termPos += l;
        count++;
    }
    Printf("\n(%d names listed)\n", count);
}

/* --------------------------------------------------------------------------
 * print a prompt and read a line of input:
 * ------------------------------------------------------------------------*/

static Void local promptForInput(moduleName)
String moduleName; {
    char promptBuffer[1000];
#if 1
    /* This is portable but could overflow buffer */
    sprintf(promptBuffer,prompt,moduleName);
#else
    /* Works on ANSI C - but pre-ANSI compilers return a pointer to
     * promptBuffer instead.
     */
    if (sprintf(promptBuffer,prompt,moduleName) >= 1000) {
        /* Reset prompt to a safe default to avoid an infinite loop */
        free(prompt);
        prompt = strCopy("? ");
        internal("Combined prompt and evaluation module name too long");
    }
#endif
    if (autoMain)
       stringInput("main\0"); else
       consoleInput(promptBuffer);
}

/* --------------------------------------------------------------------------
 * main read-eval-print loop, with error trapping:
 * ------------------------------------------------------------------------*/

static jmp_buf catch_error;             /* jump buffer for error trapping  */

static Void local interpreter(argc,argv)/* main interpreter loop           */
Int    argc;
String argv[]; {
    Int errorNumber = setjmp(catch_error);

    if (errorNumber && autoMain) {
       fprintf(stderr, "hugs +Q: compilation failed -- can't run `main'\n" );
       exit(1);
    }

    breakOn(TRUE);                      /* enable break trapping           */
    if (numScripts==0) {                /* only succeeds on first time,    */
        if (errorNumber)                /* before prelude has been loaded  */
            fatal("Unable to load prelude");
        initialize(argc,argv);
        forHelp();
    }

    /* initialize calls startupHaskell, which trashes our signal handlers */
    breakOn(TRUE);

    for (;;) {
        Command cmd;
        everybody(RESET);               /* reset to sensible initial state */
        dropScriptsFrom(numScripts-1);  /* remove partially loaded scripts */
                                        /* not counting prelude as a script*/

        promptForInput(textToStr(module(findEvalModule()).text));

        cmd = readCommand(cmds, (Char)':', (Char)'!');
#ifdef WANT_TIMER
        updateTimers();
#endif
        switch (cmd) {
            case EDIT   : editor();
                          break;
            case FIND   : find();
                          break;
            case LOAD   : clearProject();
                          forgetScriptsFrom(N_PRELUDE_SCRIPTS);
                          load();
                          break;
            case ALSO   : clearProject();
                          forgetScriptsFrom(numScripts);
                          load();
                          break;
            case RELOAD : readScripts(N_PRELUDE_SCRIPTS);
                          break;
            case PROJECT: project();
                          break;
            case SETMODULE :
                          setModule();
                          break;
            case EVAL   : evaluator();
                          break;
            case TYPEOF : showtype();
                          break;
	    case BROWSE : browse();
			  break;
#if EXPLAIN_INSTANCE_RESOLUTION
	    case XPLAIN : xplain();
			  break;
#endif
            case NAMES  : listNames();
                          break;
            case HELP   : menu();
                          break;
            case BADCMD : guidance();
                          break;
            case SET    : set();
                          break;
            case STATS:
#ifdef CRUDE_PROFILING
                          cp_show();
#endif
                          break;
            case SYSTEM : if (shellEsc(readLine()))
                              Printf("Warning: Shell escape terminated abnormally\n");
                          break;
            case CHGDIR : changeDir();
                          break;
            case INFO   : info();
                          break;
	    case PNTVER: Printf("-- Hugs Version %s\n",
				 HUGS_VERSION);
 			  break;
            case DUMP   : dumpStg();
                          break;
            case QUIT   : return;
            case COLLECT: consGC = FALSE;
                          garbageCollect();
                          consGC = TRUE;
                          Printf("Garbage collection recovered %d cells\n",
                                 cellsRecovered);
                          break;
            case NOCMD  : break;
        }
#ifdef WANT_TIMER
        updateTimers();
        Printf("Elapsed time (ms): %ld (user), %ld (system)\n",
               millisecs(userElapsed), millisecs(systElapsed));
#endif
        if (autoMain) break;
    }
    breakOn(FALSE);
}

/* --------------------------------------------------------------------------
 * Display progress towards goal:
 * ------------------------------------------------------------------------*/

static Target currTarget;
static Bool   aiming = FALSE;
static Int    currPos;
static Int    maxPos;
static Int    charCount;

Void setGoal(what, t)                  /* Set goal for what to be t        */
String what;
Target t; {
    if (quiet)
      return;
#if EXPLAIN_INSTANCE_RESOLUTION
    if (showInstRes)
      return;
#endif
    currTarget = (t?t:1);
    aiming     = TRUE;
    if (useDots) {
        currPos = strlen(what);
        maxPos  = getTerminalWidth() - 1;
        Printf("%s",what);
    }
    else
        for (charCount=0; *what; charCount++)
            Putchar(*what++);
    FlushStdout();
}

Void soFar(t)                          /* Indicate progress towards goal   */
Target t; {                            /* has now reached t                */
    if (quiet)
      return;
#if EXPLAIN_INSTANCE_RESOLUTION
    if (showInstRes)
      return;
#endif
    if (useDots) {
        Int newPos = (Int)((maxPos * ((long)t))/currTarget);

        if (newPos>maxPos)
            newPos = maxPos;

        if (newPos>currPos) {
            do
                Putchar('.');
            while (newPos>++currPos);
            FlushStdout();
        }
        FlushStdout();
    }
}

Void done() {                          /* Goal has now been achieved       */
    if (quiet)
      return;
#if EXPLAIN_INSTANCE_RESOLUTION
    if (showInstRes)
      return;
#endif
    if (useDots) {
        while (maxPos>currPos++)
            Putchar('.');
        Putchar('\n');
    }
    else
        for (; charCount>0; charCount--) {
            Putchar('\b');
            Putchar(' ');
            Putchar('\b');
        }
    aiming = FALSE;
    FlushStdout();
}

static Void local failed() {           /* Goal cannot be reached due to    */
    if (aiming) {                      /* errors                           */
        aiming = FALSE;
        Putchar('\n');
        FlushStdout();
    }
}

/* --------------------------------------------------------------------------
 * Error handling:
 * ------------------------------------------------------------------------*/

Void errHead(l)                        /* print start of error message     */
Int l; {
    failed();                          /* failed to reach target ...       */
    stopAnyPrinting();
    FPrintf(errorStream,"ERROR");

    if (scriptFile) {
        FPrintf(errorStream," \"%s\"", scriptFile);
        setLastEdit(scriptFile,l);
        if (l) FPrintf(errorStream," (line %d)",l);
        scriptFile = 0;
    }
    FPrintf(errorStream,": ");
    FFlush(errorStream);
}

Void errFail() {                        /* terminate error message and     */
    Putc('\n',errorStream);             /* produce exception to return to  */
    FFlush(errorStream);                /* main command loop               */
    longjmp(catch_error,1);
}

Void errAbort() {                       /* altern. form of error handling  */
    failed();                           /* used when suitable error message*/
    stopAnyPrinting();                  /* has already been printed        */
    errFail();
}

Void internal(msg)                      /* handle internal error           */
String msg; {
#if HUGS_FOR_WINDOWS
    char buf[300];
    wsprintf(buf,"INTERNAL ERROR: %s",msg);
    MessageBox(hWndMain, buf, appName, MB_ICONHAND | MB_OK);
#endif
    failed();
    stopAnyPrinting();
    Printf("INTERNAL ERROR: %s\n",msg);
    FlushStdout();
    longjmp(catch_error,1);
}

Void fatal(msg)                         /* handle fatal error              */
String msg; {
#if HUGS_FOR_WINDOWS
    char buf[300];
    wsprintf(buf,"FATAL ERROR: %s",msg);
    MessageBox(hWndMain, buf, appName, MB_ICONHAND | MB_OK);
#endif
    FlushStdout();
    Printf("\nFATAL ERROR: %s\n",msg);
    everybody(EXIT);
    exit(1);
}

sigHandler(breakHandler) {              /* respond to break interrupt      */
#if HUGS_FOR_WINDOWS
    MessageBox(GetFocus(), "Interrupted!", appName, MB_ICONSTOP | MB_OK);
#endif
    Hilite();
    Printf("{Interrupted!}\n");
    Lolite();
    breakOn(TRUE);  /* reinstall signal handler - redundant on BSD systems */
                    /* but essential on POSIX (and other?) systems         */
    everybody(BREAK);
    failed();
    stopAnyPrinting();
    FlushStdout();
    clearerr(stdin);
    longjmp(catch_error,1);
    sigResume;/*NOTREACHED*/
}

/* --------------------------------------------------------------------------
 * Read value from environment variable or registry:
 * ------------------------------------------------------------------------*/

String fromEnv(var,def)         /* return value of:                        */
String var;                     /*     environment variable named by var   */
String def; {                   /* or: default value given by def          */
    String s = getenv(var);     
    return (s ? s : def);
}

/* --------------------------------------------------------------------------
 * String manipulation routines:
 * ------------------------------------------------------------------------*/

static String local strCopy(s)         /* make malloced copy of a string   */
String s; {
    if (s && *s) {
        char *t, *r;
        if ((t=(char *)malloc(strlen(s)+1))==0) {
            ERRMSG(0) "String storage space exhausted"
            EEND;
        }
        for (r=t; (*r++ = *s++)!=0; ) {
        }
        return t;
    }
    return NULL;
}

/* --------------------------------------------------------------------------
 * Compiler output
 * We can redirect compiler output (prompts, error messages, etc) by
 * tweaking these functions.
 * ------------------------------------------------------------------------*/

#if REDIRECT_OUTPUT && !HUGS_FOR_WINDOWS

#ifdef HAVE_STDARG_H
#include <stdarg.h>
#else
#include <varargs.h>
#endif

/* ----------------------------------------------------------------------- */

#define BufferSize 10000              /* size of redirected output buffer  */

typedef struct _HugsStream {
    char buffer[BufferSize];          /* buffer for redirected output      */
    Int  next;                        /* next space in buffer              */
} HugsStream;

static Void   local vBufferedPrintf  ( HugsStream*, const char*, va_list );
static Void   local bufferedPutchar  ( HugsStream*, Char );
static String local bufferClear      ( HugsStream *stream );

static Void local vBufferedPrintf(stream, fmt, ap)
HugsStream* stream;
const char* fmt;
va_list     ap; {
    Int spaceLeft = BufferSize - stream->next;
    char* p = &stream->buffer[stream->next];
    Int charsAdded = vsnprintf(p, spaceLeft, fmt, ap);
    if (0 <= charsAdded && charsAdded < spaceLeft) 
        stream->next += charsAdded;
#if 1 /* we can either buffer the first n chars or buffer the last n chars */
    else
        stream->next = 0;
#endif
}

static Void local bufferedPutchar(stream, c)
HugsStream *stream;
Char        c; {
    if (BufferSize - stream->next >= 2) {
        stream->buffer[stream->next++] = c;
        stream->buffer[stream->next] = '\0';
    }
}    

static String local bufferClear(stream)
HugsStream *stream; {
    if (stream->next == 0) {
        return "";
    } else {
        stream->next = 0;
        return stream->buffer;
    }
}

/* ----------------------------------------------------------------------- */

static HugsStream outputStreamH;
/* ADR note: 
 * We rely on standard C semantics to initialise outputStreamH.next to 0.
 */

Void hugsEnableOutput(f) 
Bool f; {
    disableOutput = !f;
}

String hugsClearOutputBuffer() {
    return bufferClear(&outputStreamH);
}

#ifdef HAVE_STDARG_H
Void hugsPrintf(const char *fmt, ...) {
    va_list ap;                    /* pointer into argument list           */
    va_start(ap, fmt);             /* make ap point to first arg after fmt */
    if (!disableOutput) {
        vprintf(fmt, ap);
    } else {
        vBufferedPrintf(&outputStreamH, fmt, ap);
    }
    va_end(ap);                    /* clean up                             */
}
#else
Void hugsPrintf(fmt, va_alist) 
const char *fmt;
va_dcl {
    va_list ap;                    /* pointer into argument list           */
    va_start(ap);                  /* make ap point to first arg after fmt */
    if (!disableOutput) {
        vprintf(fmt, ap);
    } else {
        vBufferedPrintf(&outputStreamH, fmt, ap);
    }
    va_end(ap);                    /* clean up                             */
}
#endif

Void hugsPutchar(c)
int c; {
    if (!disableOutput) {
        putchar(c);
    } else {
        bufferedPutchar(&outputStreamH, c);
    }
}

Void hugsFlushStdout() {
    if (!disableOutput) {
        fflush(stdout);
    }
}

Void hugsFFlush(fp)
FILE* fp; {
    if (!disableOutput) {
        fflush(fp);
    }
}

#ifdef HAVE_STDARG_H
Void hugsFPrintf(FILE *fp, const char* fmt, ...) {
    va_list ap;             
    va_start(ap, fmt);      
    if (!disableOutput) {
        vfprintf(fp, fmt, ap);
    } else {
        vBufferedPrintf(&outputStreamH, fmt, ap);
    }
    va_end(ap);             
}
#else
Void hugsFPrintf(FILE *fp, const char* fmt, va_list)
FILE* fp;
const char* fmt;
va_dcl {
    va_list ap;             
    va_start(ap);      
    if (!disableOutput) {
        vfprintf(fp, fmt, ap);
    } else {
        vBufferedPrintf(&outputStreamH, fmt, ap);
    }
    va_end(ap);             
}
#endif

Void hugsPutc(c, fp)
int   c;
FILE* fp; {
    if (!disableOutput) {
        putc(c,fp);
    } else {
        bufferedPutchar(&outputStreamH, c);
    }
}
    
#endif /* REDIRECT_OUTPUT && !HUGS_FOR_WINDOWS */
/* --------------------------------------------------------------------------
 * Send message to each component of system:
 * ------------------------------------------------------------------------*/

Void everybody(what)            /* send command `what' to each component of*/
Int what; {                     /* system to respond as appropriate ...    */
#if 0
  fprintf ( stderr, "EVERYBODY %d\n", what );
#endif
    machdep(what);              /* The order of calling each component is  */
    storage(what);              /* important for the PREPREL command       */
    substitution(what);
    input(what);
    translateControl(what);
    linkControl(what);
    staticAnalysis(what);
    deriveControl(what);
    typeChecker(what);
    compiler(what);   
    codegen(what);
}

/* --------------------------------------------------------------------------
 * Hugs for Windows code (WinMain and related functions)
 * ------------------------------------------------------------------------*/

#if HUGS_FOR_WINDOWS
#include "winhugs.c"
#endif