File: TopLevelPolyML.sml

package info (click to toggle)
polyml 5.7.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 40,616 kB
  • sloc: cpp: 44,142; ansic: 26,963; sh: 22,002; asm: 13,486; makefile: 602; exp: 525; python: 253; awk: 91
file content (1735 lines) | stat: -rw-r--r-- 96,388 bytes parent folder | download | duplicates (4)
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
(*
    Title:      Root function for the PolyML structure
    Author:     David Matthews
    Copyright   David Matthews 2009, 2015-17

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License version 2.1 as published by the Free Software Foundation.
    
    This library 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
    Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*)

(* This contains the code for the IDE protocol as well as the normal
   Poly/ML top-level loop. *)

local
    val parseTree = ref ("", []) (* Parsetree ID and parsetrees as a list. *)

    fun runIDEProtocol () =
    let
        (* Save the last parsetree here. *)
        val lastParsetree =
            ref (case parseTree of ref(_, hd::_) => SOME hd | _ => NONE)

        val parseLock = Thread.Mutex.mutex()

        (* Access the parse tree and other information with the lock held. *)
        fun withLock f =
        let
            open Thread.Thread Thread.Mutex
            val originalState = getAttributes()
            val () = setAttributes[InterruptState InterruptDefer]
            val () = lock parseLock
            val result = f ()
            val () = unlock parseLock
            val () = setAttributes originalState
        in
            result
        end

        type basicLoc = (* Locations in request packets. *) { startOffset: FixedInt.int, endOffset: FixedInt.int }
        type compileError = { hardError: bool, location: PolyML.location, message: PolyML.pretty }

        datatype request =
            (* Requests sent by the IDE to Poly/ML. *)
            PropertyRequest (* O *)
                of { requestId: string, parseTreeId: string, location: basicLoc }
        |   MoveRequest (* M *)
                of { requestId: string, parseTreeId: string, location: basicLoc, direction: direction }
        |   TypeRequest (* T *)
                of { requestId: string, parseTreeId: string, location: basicLoc }
        |   DecRequest (* I *)
                of { requestId: string, parseTreeId: string, location: basicLoc, decType: dectype }
        |   RefRequest (* V *)
                of { requestId: string, parseTreeId: string, location: basicLoc }
        |   CompileRequest (* R *)
                of { requestId: string, fileName: string, startPosition: FixedInt.int,
                     preludeCode: string, sourceCode: string }
        |   KillRequest (* K *)
                of { requestId: string }
        |   UnknownRequest (* Provided for upwards compatibility. *)
                of { request: int, requestId: string}

        and direction = DirUp | DirLeft | DirRight | DirDown
        
        and dectype = DecLocal | DecOpen | DecParent

        and response =
            (* Replies sent from Poly/ML to the IDE. *)
            PropertyResponse (* O *)
                of { requestId: string, parseTreeId: string, location: basicLoc, commands: string list }
        |   MoveResponse  (* M *)
                of { requestId: string, parseTreeId: string, location: basicLoc }
        |   TypeResponse (* T *)
                of { requestId: string, parseTreeId: string, location: basicLoc, typeRes: PolyML.pretty option }
        |   DecResponse (* I *)
                of { requestId: string, parseTreeId: string, location: basicLoc,
                     decLocation: PolyML.location option }
        |   RefResponse (* V *)
                of { requestId: string, parseTreeId: string, location: basicLoc, references: basicLoc list }
        |   CompilerResponse (* R *)
                of { requestId: string, parseTreeId: string, finalOffset: FixedInt.int, result: compileResult }
        |   UnknownResponse (* Provided for upwards compatibility. *)
                of { request: int, requestId: string }

        and compileResult =
            Succeeded of compileError list
        |   RuntimeException of PolyML.pretty * compileError list
        |   PreludeFail of string
        |   CompileFail of compileError list
        |   CompileCancelled of compileError list


        val outputLock = Thread.Mutex.mutex()
        
        val (readRequest, sendStartedMessage, sendResponse) =
            case OS.Process.getEnv "POLYIDESOCKET" of
                NONE => (* Version 1 protocol - backwards compatibility - use stdIn/stdOut *)
                let
                    (* Separate out the output stream.  We need to interlock access to stdOut
                       to avoid user code outputing within a packet. *)
                    open TextIO TextIO.StreamIO
                    val outStream = getOutstream stdOut
                    val (writer, buffMode) = getWriter outStream
                    val TextPrimIO.WR
                        { name, chunkSize, writeVec, writeArr, block, canOutput, ioDesc, ... } = writer
                    (* Create a version of the stream that locks before actually sending output. *)
                    val lockedWriteVec =
                        case writeVec of
                            NONE => NONE
                        |   SOME writeVec =>
                                SOME(fn a => ThreadLib.protect outputLock writeVec a)
                    val lockedWriteArray =
                        case writeArr of
                            NONE => NONE
                        |   SOME writeArr =>
                                SOME(fn a => ThreadLib.protect outputLock writeArr a)
                    val lockedWriter =
                        TextPrimIO.WR { name = name, chunkSize = chunkSize,
                                        writeVec = lockedWriteVec, writeArr = lockedWriteArray,
                                        writeVecNB = NONE, writeArrNB = NONE, block = block, canOutput = canOutput,
                                        getPos = NONE, setPos = NONE, endPos = NONE, verifyPos = NONE,
                                        close = fn () => raise Fail "stdOut must not be closed", ioDesc = ioDesc }
                    (* Use this locked version for normal stdOut. *)
                    val () = setOutstream(stdOut,
                                StreamIO.mkOutstream(TextPrimIO.augmentWriter lockedWriter, buffMode))
                    (* Create an unlocked version for use within the IDE code.  When writing to this
                       stream the IDE code will first get a lock, then output the whole packet before
                       releasing the lock.  Because mutexes are not recursive we can't use the locking
                       version. *)
                    val unLockedWriter =
                        TextPrimIO.WR { name = name, chunkSize = chunkSize, writeVec = writeVec, writeArr = writeArr,
                                        writeVecNB = NONE, writeArrNB = NONE, block = block, canOutput = canOutput,
                                        getPos = NONE, setPos = NONE, endPos = NONE, verifyPos = NONE,
                                        close = fn () => raise Fail "stdOut must not be closed", ioDesc = ioDesc }

                    val inStream = stdIn

                    val outStream = StreamIO.mkOutstream(TextPrimIO.augmentWriter unLockedWriter, buffMode)

                    fun protocolError error =
                    let
                        open OS.Process
                    in
                        TextIO.print ("Protocol error: " ^ error) handle _ => ();
                        exit failure;
                        raise Fail "bad" (* Never called but sets return type as 'a *)
                    end

                    (* Reads a request.  Calls OS.Process.exit at end-of-file or on a protocol error. *)
                    fun readRequest (): request =
                    let
                        open TextIO

                        (* Returns the string as far as the next ESC and the terminator. *)
                        fun readToEscape (soFar: string, terminator) : string =
                        case input1 inStream of
                            SOME #"\u001b" =>
                            (
                                case input1 inStream of
                                    NONE => protocolError "End of file"
                                |   SOME ch =>
                                        if ch = terminator
                                        then soFar
                                        else if ch = #"\u001b" (* Escaped ESC. *)
                                        then readToEscape(soFar ^ str #"\u001b", terminator)
                                        else protocolError(str ch ^ " not " ^ str terminator)
                            )
                        |   SOME ch => readToEscape(soFar ^ str ch, terminator)
                        |   NONE => protocolError "End of file"

                        (* Parse an integer.  Returns zero if it isn't a valid int. *)
                        fun getInt termCh : FixedInt.int =
                            case FixedInt.fromString (readToEscape("", termCh)) of
                                NONE => 0
                            |   SOME i => i

                        val () =
                            case input1 inStream of
                                NONE => OS.Process.exit OS.Process.success (* Close down. *)
                            |   SOME #"\u001b" => () (* Escape- start of packet. *)
                            |   SOME ch => protocolError(str ch ^ " not ESCAPE at start of packet")
                        val startCh = (* Request code *)
                            case input1 inStream of
                                NONE => protocolError "End of file"
                            |   SOME ch => ch
                    in
                        case startCh of
                            #"R" =>
                            let (* Compile request. *)
                                (* Begin a new compilation. *)
                                val requestId = readToEscape("", #",")
                                val fileName = readToEscape("", #",")
                                val startPosition = getInt #","
                                (* The next two are the lengths *)
                                val preludeLength = getInt #","
                                val sourceLength = getInt #","
                                (* *)
                                val preludeCode = TextIO.inputN(inStream, FixedInt.toInt preludeLength)
                                val _ = readToEscape("", #",") (* Should be empty - check? *)
                                val sourceText = TextIO.inputN(inStream, FixedInt.toInt sourceLength)
                                val _ = readToEscape("", #"r") (* Should be empty - check? *)
                            in
                                CompileRequest { requestId = requestId, fileName = fileName, startPosition = startPosition,
                                         preludeCode = preludeCode, sourceCode = sourceText }
                            end

                            (* Navigation functions. *)
            
                        |   #"M" =>
                            let
                                val requestId = readToEscape("", #",")
                                val parseTreeId = readToEscape("", #",")
                                val startOffset = getInt #","
                                val endOffset = getInt #","
                                val requestType =
                                    case readToEscape("", #"m") of
                                        "N" => DirRight
                                    |   "P" => DirLeft
                                    |   "U" => DirUp
                                    |   _(*"C"*) => DirDown
                            in
                                MoveRequest{
                                    requestId = requestId, parseTreeId = parseTreeId, direction= requestType,
                                    location = { startOffset = startOffset, endOffset = endOffset }
                                    }
                            end

                            (* Print the type of the selected node. *)
                        |   #"T" =>
                            let
                                val requestId = readToEscape("", #",")
                                val parseTreeId = readToEscape("", #",")
                                val startOffset = getInt #","
                                val endOffset = getInt #"t"
                            in
                                TypeRequest{
                                    requestId = requestId, parseTreeId = parseTreeId,
                                    location = { startOffset = startOffset, endOffset = endOffset }
                                    }
                            end

                            (* Print the declaration location of the selected node. *)
                        |   #"I" =>
                            let
                                val requestId = readToEscape("", #",")
                                val parseTreeId = readToEscape("", #",")
                                val startOffset = getInt #","
                                val endOffset = getInt #","
                                val decType =
                                    case readToEscape("", #"i") of
                                        "J" => DecOpen
                                    |   "S" => DecParent
                                    |   _ (*"I"*) => DecLocal
                            in
                                DecRequest{
                                    requestId = requestId, parseTreeId = parseTreeId, decType = decType,
                                    location = { startOffset = startOffset, endOffset = endOffset }
                                    }
                            end

                            (* Return the local references to the given identifier. *)
                        |   #"V" =>
                            let
                                val requestId = readToEscape("", #",")
                                val parseTreeId = readToEscape("", #",")
                                val startOffset = getInt #","
                                val endOffset = getInt #"v"
                            in
                                RefRequest{
                                    requestId = requestId, parseTreeId = parseTreeId,
                                    location = { startOffset = startOffset, endOffset = endOffset }
                                    }
                            end

                        |   #"O" => (* Print list of valid commands. *)
                            let
                                val requestId = readToEscape("", #",")
                                val parseTreeId = readToEscape("", #",")
                                val startOffset = getInt #","
                                val endOffset = getInt #"o"
                            in
                                PropertyRequest{
                                    requestId = requestId, parseTreeId = parseTreeId,
                                    location = { startOffset = startOffset, endOffset = endOffset }
                                    }
                            end

                        |   #"K" => (* Cancel request. *)
                                KillRequest { requestId = readToEscape ("", #"k") }

                        |   ch => (* Something else.  Reply with empty response. *)
                            let
                                (* Unlike the other cases we don't know what may follow ESCAPE. *)
                                val terminator = Char.toLower ch
                                fun skipToTerminator () =
                                case input1 inStream of
                                    SOME #"\u001b" =>
                                    (
                                        case input1 inStream of
                                            NONE => protocolError "End of file"
                                        |   SOME ch =>
                                                if ch = terminator
                                                then () (* Found the end. *)
                                                else (* Some internal escape code. *) skipToTerminator()
                                    )
                                |   SOME _ => skipToTerminator ()
                                |   NONE => protocolError "End of file"
                            in
                                skipToTerminator ();
                                UnknownRequest { request = Char.ord ch, requestId = "" }
                            end
                    end (* readRequest *)

                    fun sendStartedMessage () = 
                    let 
                        fun print s = TextIO.StreamIO.output(outStream, s)
                        fun printEsc ch = print (String.concat["\u001b", String.str ch])
                        fun sendResponse () =
                        ( (* send the version number of the protocol *)
                            printEsc #"H"; print "1.0.0"; printEsc #"h";
                            TextIO.StreamIO.flushOut outStream
                        )
                    in
                        ThreadLib.protect outputLock sendResponse ()
                    end

                    (* Send a reply packet. *)
                    fun sendResponse response =
                    let
                        fun print s = TextIO.StreamIO.output(outStream, s)
                        fun printEsc ch = print (String.concat["\u001b", String.str ch])

                        fun printLocation {startOffset, endOffset } =
                            print (String.concat[FixedInt.toString startOffset, "\u001b,", FixedInt.toString endOffset])

                        and printFullLocation { file, startLine, startPosition, endPosition, ...} =
                        (
                            print file; (* TODO double any escapes. *) printEsc #",";
                            print (FixedInt.toString startLine); printEsc #",";
                            print (FixedInt.toString startPosition); printEsc #",";
                            print (FixedInt.toString endPosition)
                        )

                        fun makeResponse (PropertyResponse { requestId, parseTreeId, location, commands }) =
                            let
                                fun printCommand comm = (printEsc #","; print comm)
                            in
                                printEsc #"O";
                                print requestId; printEsc #",";
                                print parseTreeId; printEsc #",";
                                printLocation location;
                                List.app printCommand commands;
                                printEsc #"o"
                            end

                        |   makeResponse (MoveResponse { requestId, parseTreeId, location }) =
                            (
                                printEsc #"M";
                                print requestId; printEsc #",";
                                print parseTreeId; printEsc #",";
                                printLocation location;
                                printEsc #"m"
                            )

                        |   makeResponse (TypeResponse { requestId, parseTreeId, location, typeRes }) =
                            let
                                fun prettyAsString message =
                                let
                                    val result = ref []
                                    fun doPrint s = result := s :: ! result
                                    val () = PolyML.prettyPrint(doPrint, !PolyML.Compiler.lineLength) message
                                in
                                    String.concat(List.rev(! result))
                                end
                            in
                                printEsc #"T";
                                print requestId; printEsc #",";
                                print parseTreeId; printEsc #",";
                                printLocation location;
                                case typeRes of
                                    NONE => ()
                                |   SOME typeRes =>
                                    (
                                        printEsc #",";
                                        print(prettyAsString typeRes)
                                    );
                                printEsc #"t"
                            end

                        |   makeResponse (DecResponse { requestId, parseTreeId, location, decLocation }) =
                            (
                                printEsc #"I";
                                print requestId; printEsc #",";
                                print parseTreeId; printEsc #",";
                                printLocation location;
                                case decLocation of
                                    SOME location => (printEsc #","; printFullLocation location)
                                |   NONE => ();
                                printEsc #"i"
                            )

                        |   makeResponse (RefResponse { requestId, parseTreeId, location, references }) =
                            (
                                printEsc #"V";
                                print requestId; printEsc #",";
                                print parseTreeId;  printEsc #",";
                                printLocation location;
                                List.app (fn loc => (printEsc #","; printLocation loc)) references;
                                printEsc #"v"
                            )

                        |   makeResponse (CompilerResponse { requestId, parseTreeId, finalOffset, result }) =
                            let
                                (* Pretty print a message and return the output string. *)
                                fun prettyMarkupAsString message =
                                let
                                    val result = ref []
                                    fun doPrint s = result := s :: ! result
                                    val () = PolyML.prettyPrintWithIDEMarkup(doPrint, !PolyML.Compiler.lineLength) message
                                in
                                    String.concat(List.rev(! result))
                                end

                                fun printError { hardError, location, message } =
                                (
                                    printEsc #"E";
                                    if hardError then print "E" else print "W";
                                    printEsc #",";
                                    printFullLocation location;
                                    printEsc #";"; (* N.B. Semicolon here, not comma. *)
                                    print (prettyMarkupAsString message); (* May include markup *)
                                    printEsc #"e"
                                )
                                fun printOffset() = (printEsc #","; print (FixedInt.toString finalOffset))
                                fun printErrors errors = (List.app printError errors)
                            in
                                printEsc #"R";
                                print requestId; printEsc #",";
                                print parseTreeId; printEsc #",";
                                case result of
                                    Succeeded errors => (print "S"; printOffset(); printEsc #";"; printErrors errors)
                                |   RuntimeException (s, errors) =>
                                    (
                                        print "X"; printOffset(); 
                                        printEsc #";";
                                        printEsc #"X"; print(prettyMarkupAsString s); (* May include markup *)
                                        printEsc #"x"; 
                                        printErrors errors
                                    )
                                |   PreludeFail s =>
                                    ( print "L"; printOffset(); printEsc #";"; print s (* May include markup *) )
                                |   CompileFail errors =>
                                    ( print "F"; printOffset(); printEsc #";"; printErrors errors )
                                |   CompileCancelled errors =>
                                    ( print "C"; printOffset(); printEsc #";"; printErrors errors );
                                printEsc #"r"
                             end

                        |   makeResponse (UnknownResponse { request, ... }) =
                            let
                                val startCh = Char.chr request
                            in
                                (* Response to unknown command - return empty result. *)
                                ( printEsc startCh; printEsc (Char.toLower startCh))
                            end

                        fun sendResponse () =
                        (
                            makeResponse response handle _ => protocolError "Exception";
                            TextIO.StreamIO.flushOut outStream
                        )
                    in
                        (* Sending the response packet must be atomic with respect to any other
                           output to stdOut. *)
                        ThreadLib.protect outputLock sendResponse ()
                    end (* sendResponse *)

                in
                    (readRequest, sendStartedMessage, sendResponse)
                end

            |   SOME portNo =>
                (* Version 2 protocol - uses ASN1 binary over a socket.*)
                let
                    val prefBuffSize = 4096 (* Get this from somewhere? *)
                    val socket = INetSock.TCP.socket(): Socket.active INetSock.stream_sock
                    (* We don't have a stream to produce error messages so simply fail if
                       we get an exception here. *)
                    val localhost = NetHostDB.addr (valOf(NetHostDB.getByName "localhost"))
                    val port = valOf(Int.fromString portNo)
                    val () = Socket.connect(socket, INetSock.toAddr(localhost, port))
                    (* Construct the readers and writers. *)

                    fun sendASN1(v: Word8Vector.vector list) =
                    let
                        open Word8VectorSlice
                        (* Write the whole data, in chunks if necessary. *)
                        fun sendSlice slice =
                            if length slice = 0
                            then ()
                            else sendSlice(subslice(slice, Socket.sendVec(socket, slice), NONE))
                    in
                        sendSlice(Word8VectorSlice.full(Word8Vector.concat v))
                    end

                    fun readVecFromSocket(n: int): Word8Vector.vector = Socket.recvVec(socket, n)

                    open TextIO Asn1

                    local (* Interlocked writer for TextIO.stdOut *)
                        (* Whenever we write plain text we package it as an ASN1 packet. *)
                        fun writeVecToSocket(v: CharVectorSlice.slice) =
                            (
                                sendASN1(encodeItem(Application(1, Primitive), [encodeString(CharVectorSlice.vector v)]));
                                CharVectorSlice.length v (* It's written it all. *)
                            )
                        val lockedWriteVec = ThreadLib.protect outputLock writeVecToSocket
                        val lockedWriter =
                            TextPrimIO.WR {
                                name = "TextIO.stdOut", chunkSize = prefBuffSize,
                                writeVec = SOME lockedWriteVec, writeArr = NONE,
                                writeVecNB = NONE, writeArrNB = NONE, block = NONE, canOutput = NONE,
                                getPos = NONE, setPos = NONE, endPos = NONE, verifyPos = NONE,
                                close = fn () => raise Fail "stdOut must not be closed",
                                ioDesc = SOME(Socket.ioDesc socket) }
                    in
                        (* Use this locked version for normal stdOut. *)
                        val () = setOutstream(stdOut,
                                    StreamIO.mkOutstream(TextPrimIO.augmentWriter lockedWriter, IO.LINE_BUF))
                    end

                    local
                        (* Create a functional binary stream *)
                        val reader =
                            BinPrimIO.RD {
                                name = "socket", chunkSize = prefBuffSize,
                                readVec = SOME readVecFromSocket, readArr = NONE, readVecNB = NONE,
                                readArrNB = NONE, block = NONE,
                                canInput = NONE, avail = fn _ => NONE,
                                getPos = NONE, setPos = NONE, endPos = NONE, verifyPos = NONE,
                                close = fn _ => (), ioDesc = SOME(Socket.ioDesc socket)
                            }
                        val binStream =
                            BinIO.StreamIO.mkInstream(BinPrimIO.augmentReader reader, Word8Vector.fromList [])
                    in
                        val inStream = ref binStream
                    end

                    fun protocolError error =
                    let
                        open OS.Process
                    in
                        TextIO.print ("Protocol error: " ^ error) handle _ => ();
                        exit failure
                    end

                    (* Reads a request.  Calls OS.Process.exit at end-of-file or on a protocol error. *)
                    fun readRequest (): request =
                    let
                        open Asn1

                        (* Read the ASN1 header to get the tag and then read the data.
                           Position the stream ready to read the next request. *)
                        val (requestTag, data) =
                            case readHeader BinIO.StreamIO.input1 (!inStream) of
                                NONE => (* If we had EOF here it's probably because we've closed. *)
                                    OS.Process.exit OS.Process.success (* Close down. *)
                            |   SOME((tag, length), afterHdr) =>
                                let
                                    val (vector, afterBlock) =
                                        BinIO.StreamIO.inputN(afterHdr, length)
                                in
                                    if Word8Vector.length vector = length
                                    then ()
                                    else protocolError "Stream closed";
                                    inStream := afterBlock;
                                    (tag, vector)
                                end

                        fun splitSequence v =
                            case decodeItem v of
                                SOME{tag, data, remainder} =>
                                    (tag, data) :: splitSequence remainder
                            |   NONE => []

                        (* See if an item is present and return it if it is. *)
                        fun findData tag list =
                            Option.map #2 (List.find (fn (t, _) => t = tag) list)

                        fun findString tag list =
                            Option.map decodeString (findData tag list)
                        and findInt tag list =
                            Option.map (FixedInt.fromInt o decodeInt) (findData tag list)
                    in
                        case requestTag of
                            Application(3, _) => (* Compilation request. *)
                            let
                                val tdList = splitSequence(Word8VectorSlice.full data)
                                (* Request id *)
                                val reqId = findString (Application(1, Primitive)) tdList
                                (* File name - optional, default "" *)
                                val fileName = getOpt(findString (Context(1, Primitive)) tdList, "")
                                (* Start position - optional, default 0 *)
                                val startPosition = getOpt(findInt (Context(2, Primitive)) tdList, 0)
                                (* Prelude code - optional, default "" *)
                                val preludeCode = getOpt(findString (Context(3, Primitive)) tdList, "")
                                (* Source code *)
                                val source = findString (Context(4, Primitive)) tdList
                            in
                                case (reqId, source) of
                                    (SOME requestId, SOME sourceText) =>
                                        CompileRequest { requestId = requestId, fileName = fileName, startPosition = startPosition,
                                                 preludeCode = preludeCode, sourceCode = sourceText }
                                |   (SOME requestId, _) => UnknownRequest { request = 3, requestId = requestId }
                                |   _ => UnknownRequest { request = 3, requestId = "" } (* Malformed *)
                            end

                        |   Application(4, _) => (* Return the type of the selected node. *)
                            let
                                val tdList = splitSequence(Word8VectorSlice.full data)
                                (* Request id *)
                                val reqId = findString (Application(1, Primitive)) tdList
                                (* Parse id *)
                                val parseId = findString (Application(2, Primitive)) tdList
                                (* Start offset *)
                                val startOff = findInt (Context(1, Primitive)) tdList
                                (* End offset *)
                                val endOff = findInt (Context(2, Primitive)) tdList
                            in
                                case (reqId, parseId, startOff, endOff) of
                                    (SOME requestId, SOME parseTreeId, SOME startOffset, SOME endOffset) =>
                                        TypeRequest{
                                            requestId = requestId, parseTreeId = parseTreeId,
                                            location = { startOffset = startOffset, endOffset = endOffset }
                                            }
                                |   (SOME requestId, _, _, _) => UnknownRequest { request = 4, requestId = requestId }
                                |   _ => UnknownRequest { request = 4, requestId = "" } (* Malformed *)
                            end

                        |   Application(5, _) => (* Move request. *)
                            let
                                val tdList = splitSequence(Word8VectorSlice.full data)
                                (* Request id *)
                                val reqId = findString (Application(1, Primitive)) tdList
                                (* Parse id *)
                                val parseId = findString (Application(2, Primitive)) tdList
                                (* Start offset *)
                                val startOff = findInt (Context(1, Primitive)) tdList
                                (* End offset *)
                                val endOff = findInt (Context(2, Primitive)) tdList
                                (* Move direction *)
                                val dir = findInt (Context(3, Primitive)) tdList
                            in
                                case (reqId, parseId, startOff, endOff, dir) of
                                    (SOME requestId, SOME parseTreeId, SOME startOffset,
                                     SOME endOffset, SOME dir) =>
                                    let
                                        val dirn =
                                            case dir of
                                                1 => DirUp
                                            |   2 => DirLeft
                                            |   3 => DirRight
                                            |   _ (*4*) => DirDown
                                    in
                                        MoveRequest{
                                            requestId = requestId, parseTreeId = parseTreeId, direction = dirn,
                                            location = { startOffset = startOffset, endOffset = endOffset }
                                            }
                                    end
                                |   (SOME requestId, _, _, _, _) => UnknownRequest { request = 5, requestId = requestId }
                                |   _ => UnknownRequest { request = 5, requestId = "" } (* Malformed *)

                            end

                        |   Application(6, _) => (* Declaration location for variables. *)
                            let
                                val tdList = splitSequence(Word8VectorSlice.full data)
                                (* Request id *)
                                val reqId = findString (Application(1, Primitive)) tdList
                                (* Parse id *)
                                val parseId = findString (Application(2, Primitive)) tdList
                                (* Start offset *)
                                val startOff = findInt (Context(1, Primitive)) tdList
                                (* End offset *)
                                val endOff = findInt (Context(2, Primitive)) tdList
                                (* Dec type *)
                                val dt = findInt (Context(3, Primitive)) tdList
                            in
                                case (reqId, parseId, startOff, endOff, dt) of
                                    (SOME requestId, SOME parseTreeId, SOME startOffset,
                                     SOME endOffset, SOME dect) =>
                                    let
                                        val decType =
                                            case dect of
                                                2 => DecOpen
                                            |   3 => DecParent
                                            |   _ (*1*) => DecLocal
                                    in
                                        DecRequest{
                                            requestId = requestId, parseTreeId = parseTreeId, decType = decType,
                                            location = { startOffset = startOffset, endOffset = endOffset }
                                            }
                                    end
                                |   (SOME requestId, _, _, _, _) => UnknownRequest { request = 6, requestId = requestId }
                                |   _ => UnknownRequest { request = 6, requestId = "" } (* Malformed *)
                            end

                        |   Application(7, _) => (* List the references to a variable. *)
                            let
                                val tdList = splitSequence(Word8VectorSlice.full data)
                                (* Request id *)
                                val reqId = findString (Application(1, Primitive)) tdList
                                (* Parse id *)
                                val parseId = findString (Application(2, Primitive)) tdList
                                (* Start offset *)
                                val startOff = findInt (Context(1, Primitive)) tdList
                                (* End offset *)
                                val endOff = findInt (Context(2, Primitive)) tdList
                            in
                                case (reqId, parseId, startOff, endOff) of
                                    (SOME requestId, SOME parseTreeId, SOME startOffset, SOME endOffset) =>
                                        RefRequest{
                                            requestId = requestId, parseTreeId = parseTreeId,
                                            location = { startOffset = startOffset, endOffset = endOffset }
                                            }
                                |   (SOME requestId, _, _, _) => UnknownRequest { request = 7, requestId = requestId }
                                |   _ => UnknownRequest { request = 7, requestId = "" } (* Malformed *)
                            end

                        |   Universal(tagNo, _) => UnknownRequest { request = tagNo, requestId = "" }
                        |   Application(tagNo, _) => UnknownRequest { request = tagNo, requestId = "" }
                        |   Context(tagNo, _) => UnknownRequest { request = tagNo, requestId = "" }
                        |   Private(tagNo, _) => UnknownRequest { request = tagNo, requestId = "" }
                        (*case startCh of
                        |   #"O" => (* Print list of valid commands. *)
                            let
                                val requestId = readToEscape("", #",")
                                val parseTreeId = readToEscape("", #",")
                                val startOffset = getInt #","
                                val endOffset = getInt #"o"
                            in
                                PropertyRequest{
                                    requestId = requestId, parseTreeId = parseTreeId,
                                    location = { startOffset = startOffset, endOffset = endOffset }
                                    }
                            end

                        |   #"K" => (* Cancel request. *)
                                KillRequest { requestId = readToEscape ("", #"k") }
                        *)
                    end (* readRequest *)

                    fun sendStartedMessage () = 
                    let
                        fun sendResponse () =
                            sendASN1(encodeItem(Application(2, Primitive), [encodeString "1.0.0"]))
                    in
                        ThreadLib.protect outputLock sendResponse ()
                    end

                    (* Send a reply packet. *)
                    fun sendResponse response =
                    let
                        fun encodeFullLocation { file, startLine, startPosition, endPosition, ...} =
                        let
                            val encFile =
                                if file = "" then [] else encodeItem(Context(1, Primitive), [encodeString file])
                            val encLine =
                                if startLine = 0 then [] else encodeItem(Context(2, Primitive), [encodeInt(FixedInt.toInt startLine)])
                            val encStart =
                                if startPosition = 0 then [] else encodeItem(Context(3, Primitive), [encodeInt(FixedInt.toInt startPosition)])
                            val encEnd =
                                if endPosition = 0 then [] else encodeItem(Context(4, Primitive), [encodeInt(FixedInt.toInt endPosition)])
                        in
                            encFile @ encLine @ encStart @ encEnd
                        end

                        and encodeLocation {startOffset, endOffset } =
                                encodeItem(Context(3, Primitive), [encodeInt(FixedInt.toInt startOffset)]) @
                                encodeItem(Context(4, Primitive), [encodeInt(FixedInt.toInt endOffset)])

                        and encodeRequestId requestId =
                            encodeItem(Application(20, Primitive), [encodeString requestId])
                            
                        and encodeParseId parseId =
                            encodeItem(Application(21, Primitive), [encodeString parseId])

                        fun mapEnc _ [] = []
                        |   mapEnc f (hd :: tl) = f hd @ mapEnc f tl

                        (* Turn a pretty-print structure into text, stripping out mark-up. *)
                        (* TODO: We could return the "pretty" structure and have the IDE format it. *)
                        fun prettyAsString message =
                        let
                            val result = ref []
                            fun doPrint s = result := s :: ! result
                            val () = PolyML.prettyPrint(doPrint, 120(*!PolyML.Compiler.lineLength*)) message
                        in
                            String.concat(List.rev(! result))
                        end

                        fun makeResponse (CompilerResponse { requestId, parseTreeId, finalOffset, result }) =
                            let
                                fun encodeError { hardError, location, message } =
                                    encodeItem(Context(4, Constructed),
                                        encodeItem(Context(1, Primitive), [encodeBool hardError]) @
                                        encodeItem(Context(3, Constructed), encodeFullLocation location) @
                                        encodeItem(Context(2, Primitive), [encodeString(prettyAsString message)])
                                        )

                                val (resultCode, resultData) =
                                    case result of
                                        Succeeded errors =>
                                            (0, mapEnc encodeError errors)
                                    |   RuntimeException (s, errors) =>
                                            (1, encodeItem(Context(3, Primitive),
                                                [encodeString(prettyAsString s)]) @ mapEnc encodeError errors)
                                    |   PreludeFail s =>
                                            (2, encodeItem(Context(3, Primitive), [encodeString s]))
                                    |   CompileFail errors =>
                                            (3, mapEnc encodeError errors)
                                    |   CompileCancelled errors =>
                                            (4, mapEnc encodeError errors)
                            in
                                sendASN1(encodeItem(Application(3, Constructed),
                                    encodeRequestId requestId @ encodeParseId parseTreeId @
                                    encodeItem(Context(1, Primitive), [encodeInt(FixedInt.toInt finalOffset)]) @
                                    encodeItem(Context(2, Primitive), [encodeInt(FixedInt.toInt resultCode)]) @
                                    resultData))
                            end

                        |   makeResponse (PropertyResponse { requestId, parseTreeId, location, commands }) =
                            let
                                fun encCommand c = encodeItem(Context(2, Primitive), [encodeString c])
                            in
                                sendASN1(encodeItem(Application(4, Constructed),
                                    encodeRequestId requestId @ encodeParseId parseTreeId @
                                    encodeItem(Context(1, Constructed), encodeLocation location) @
                                    mapEnc encCommand commands))
                            end

                        |   makeResponse (MoveResponse { requestId, parseTreeId, location }) =
                                sendASN1(encodeItem(Application(7, Constructed),
                                    encodeRequestId requestId @ encodeParseId parseTreeId @
                                    encodeItem(Context(1, Constructed), encodeLocation location)))

                        |   makeResponse (TypeResponse { requestId, parseTreeId, location, typeRes }) =
                            let
                                val typeData =
                                    case typeRes of
                                        NONE => []
                                    |   SOME t => encodeItem(Context(2, Primitive), [encodeString(prettyAsString t)])
                            in
                                sendASN1(encodeItem(Application(8, Constructed),
                                    encodeRequestId requestId @ encodeParseId parseTreeId @
                                    encodeItem(Context(1, Constructed), encodeLocation location) @ typeData))
                            end

                        |   makeResponse (DecResponse { requestId, parseTreeId, location, decLocation }) =
                            let
                                val decData =
                                    case decLocation of
                                        NONE => []
                                    |   SOME l => encodeItem(Context(2, Constructed), encodeFullLocation l)
                            in
                                sendASN1(encodeItem(Application(9, Constructed),
                                    encodeRequestId requestId @ encodeParseId parseTreeId @
                                    encodeItem(Context(1, Constructed), encodeLocation location) @ decData))
                            end

                        |   makeResponse (RefResponse { requestId, parseTreeId, location, references }) =
                            let
                                fun encLoc l = encodeItem(Context(2, Constructed), encodeLocation l)
                            in
                                sendASN1(encodeItem(Application(10, Constructed),
                                    encodeRequestId requestId  @ encodeParseId parseTreeId @
                                    encodeItem(Context(1, Constructed), encodeLocation location) @
                                    mapEnc encLoc references))
                            end

                        |   makeResponse (UnknownResponse { requestId, ... }) =
                                (* Send an Error packet. *)
                                sendASN1(encodeItem(Application(0, Constructed),
                                    if requestId = "" then []
                                    else encodeRequestId requestId))

                        fun sendResponse () =
                        (
                            makeResponse response handle _ => protocolError "Exception"
                        )
                    in
                        (* Sending the response packet must be atomic with respect to any other
                           output to stdOut. *)
                        ThreadLib.protect outputLock sendResponse ()
                    end (* sendResponse *)
                in
                    (readRequest, sendStartedMessage, sendResponse)
                end

        (* Get the current parse tree and identifier. *)
        fun getCurrentParse() =
            withLock (fn () => let val (id, trees) = ! parseTree in (trees, ! lastParsetree, id) end)
        (* Update lastParsetree if the id is still valid. *)
        fun updateLastParse(id, pt) =
        let
            fun f () =
            if id = #1 (! parseTree) then lastParsetree := pt else ()
        in
            withLock f
        end
        (* Set parse tree and ID as a result of a compilation.  Sets lastParsetree to the
           head of the updated parse tree. *)
        fun setParseTree(pt, id) =
        let
            fun f () =
            (
                parseTree := (id, pt); 
                case pt of
                    [] => lastParsetree := NONE
                |   hd :: _ => lastParsetree := SOME hd
            )
        in
            withLock f
        end

        (* The source text may consist of several "programs".  When we compile a "program" we
           have to provide a way for the parsetree for this "program" to navigate to others
           even though they won't have been compiled yet.  This enables it to work. *)
        (* We have to return functions for the parent, for the next sibling even if there
           isn't one and for the previous sibling. *)
        fun toplevelParseTree (parseRootRef as ref currentList) =
        let
            open PolyML
            (* This is called when we have processed the previous "programs" but
               not yet processed this one. *)
            fun makelist([], _) = (* Shouldn't happen *) raise Fail "Null list"
            |   makelist(l as (locn, props) :: tl, previous) =
                let
                    fun this () = makelist(l, previous)
                    (* If there is another item in the list we need a
                       property that moves there whose "previous" property
                       comes here. *)
                    val next =
                        case tl of
                            [] => []
                        |   _ => [PTnextSibling(
                                    fn () => makelist(tl, [PTpreviousSibling this]))]
                in
                    (locn, previous @ next @ props)
                end
            fun parent () =
                case ! parseRootRef of
                    [] => raise Fail "Empty Tree"
                |   trees as (hd :: _) =>
                    let
                        (* Navigation for one or more topdecs. *)
                        val fullLoc =
                            case (hd, List.last trees) of
                                (({ file, startLine, startPosition, ... }, _),
                                 ({ endLine, endPosition, ... }, _)) =>
                                {
                                    file=file, startLine=startLine,
                                    startPosition=startPosition,
                                    endLine=endLine, endPosition=endPosition
                                }
                    in
                        (fullLoc, [PTfirstChild(fn () => makelist(trees, []))])
                    end

            val itemCount = List.length currentList

            fun moveToNth n =
            let
                fun move (tree, 0) = tree
                |   move ((loc, opts), n) =
                    case List.find(fn PTnextSibling _ => true | _ => false) opts of
                        NONE =>
                        let
                            (* We have to put a dummy item in at the end since when we
                               created the parent properties for the last "program" we will
                               have passed in a "next" entry even though there wasn't
                               actually a "next". *)
                            val { file, startLine, startPosition, ... } = loc
                            val lastPos =
                                { file = file, startLine = startLine, endLine = startLine,
                                  startPosition = startPosition, endPosition = startPosition }
                            val opts =
                                List.filter(fn PTparent _ => true | PTpreviousSibling _ => true | _ => false) opts
                        in
                            (lastPos, opts)
                        end
                    |   SOME (PTnextSibling f) => move(f(), n-1)
                    |   SOME _ => raise Match (* Shouldn't happen *)
            in
                case ! parseRootRef of
                    [] => raise Fail "Empty Tree"
                |   trees => move(makelist(trees, []), n)
            end
            val previous =
                case currentList of
                    [] => NONE (* This is the first. *)
                |   _ => SOME(fn () => moveToNth(itemCount-1))
            fun next () = moveToNth(itemCount+1)
        in
            { parent = SOME parent, next = SOME next, previous = previous }
        end

        (* Move in the selected direction.  Returns the tree as the result of the move. *)
        fun navigateTo(searchLocation as {startOffset:FixedInt.int, endOffset:FixedInt.int}, lastParsetree) =
        case lastParsetree of
            NONE => NONE
        |   SOME({ startPosition, endPosition, ... }, tree) =>
            let
                open PolyML
                datatype direction = Up | Down | Left | Right
                fun find([], _) = NONE (* No change *)
                |   find(PTparent p :: _, Up) = SOME p
                |   find(PTpreviousSibling p :: _, Left) = SOME p
                |   find(PTnextSibling p :: _, Right) = SOME p
                |   find(PTfirstChild p :: _, Down) = SOME p
                |   find(_ :: tl, dir) = find (tl, dir)
            in
                if startOffset = startPosition andalso endOffset = endPosition
                then (* We're there already. *) lastParsetree
                else if startOffset >= startPosition andalso endOffset <= endPosition
                then (* It's this node or a child. *)
                    let
                        val child = find(tree, Down)
                    in
                        (* See if the element we want is actually a child. *)
                        case child of
                            SOME child =>
                            let
                                (* See which child it is. *)
                                fun findChild(location as {startPosition, endPosition, ...}, child) =
                                    if startOffset >= startPosition andalso endOffset <= endPosition
                                    then SOME (location, child)
                                    else
                                    case find(child, Right) of
                                        NONE => NONE
                                    |   SOME next => findChild(next())
                            in
                                case findChild(child()) of
                                    NONE => lastParsetree (* In this *)
                                |   SOME child => navigateTo(searchLocation, SOME child)
                            end
                        |   NONE => lastParsetree (* No children. *)
                    end
                else (* Must go out. *)
                (
                    case find(tree, Up) of
                        SOME p => navigateTo(searchLocation, SOME(p()))
                    |   NONE => NONE (* Not found *)
                )
            end

        (* Main protocol loop. *)
        fun runProtocol currentCompilation =
        let
            (* Return the location of the given tree. *)
            fun treeLocation NONE = {startOffset = 0, endOffset = 0}
            |   treeLocation (SOME ({startPosition, endPosition, ...}, _)) =
                        {startOffset = startPosition, endOffset = endPosition}
        in
            case readRequest () of
                PropertyRequest { requestId: string, parseTreeId: string, location } =>
                let (* Properties of selected node. *)
                    (* Get the current parse tree and check the ID matches *)
                    val (_, lastParsetree, currentParseID) = getCurrentParse()
                    val (commands, location) =
                        if parseTreeId = currentParseID
                        then
                        let
                            val newTree = navigateTo(location, lastParsetree)
                            (* Update the last tree if it's still valid. *)
                            val () = updateLastParse(currentParseID, newTree)
                            val commands =
                                case newTree of
                                    NONE => []
                                |   (SOME(_, tree)) =>
                                    let
                                        open PolyML
                                        fun printCode(PTparent _, rest) = "U" :: rest
                                        |   printCode(PTpreviousSibling _, rest) = "P" :: rest
                                        |   printCode(PTnextSibling _, rest) = "N" :: rest
                                        |   printCode(PTfirstChild _, rest) = "C" :: rest
                                        |   printCode(PTtype _, rest) = "T" :: rest
                                        |   printCode(PTdeclaredAt _, rest) = "I" :: rest
                                        |   printCode(PTopenedAt _, rest) = "J" :: rest
                                        |   printCode(PTstructureAt _, rest) = "S" :: rest
                                        |   printCode(PTreferences(_, _::_), rest) = "V" :: rest
                                                (* Only include references if there is at least one
                                                   local reference. *)
                                        |   printCode(PTreferences(_, []), rest) = rest
                                        |   printCode(PTprint _, rest) = rest
                                        |   printCode(PTbreakPoint _, rest) = rest
                                        |   printCode(PTcompletions _, rest) = rest
                                        |   printCode(PTdefId _, rest) = rest
                                        |   printCode(PTrefId _, rest) = rest
                                    in
                                        List.foldl printCode [] tree
                                    end
                        in
                            (commands, treeLocation newTree)
                        end
                        else ([], { startOffset = 0, endOffset = 0 }) (* Wrong ID. *)
                in
                    sendResponse(
                        PropertyResponse {
                            requestId = requestId, parseTreeId = currentParseID,
                            location = location, commands = commands
                        });
                    runProtocol currentCompilation
                end

            |   MoveRequest { requestId, parseTreeId, location, direction } =>
                let  (* Get location after a move relative to a selected node. *)
                    val (_, lastParsetree, currentParseID) = getCurrentParse()
                    val newLocation =
                        if parseTreeId = currentParseID
                        then
                        let
                            (* Move to the given location, then move in the required direction. *)
                            val newTree = 
                                case navigateTo(location, lastParsetree) of
                                    NONE => NONE
                                |   SOME(location, tree) =>
                                    let
                                        open PolyML
                                        fun find([], _) = (location, tree) (* No change *)
                                        |   find(PTparent p :: _, DirUp) = p()
                                        |   find(PTpreviousSibling p :: _, DirLeft) = p()
                                        |   find(PTnextSibling p :: _, DirRight) = p()
                                        |   find(PTfirstChild p :: _, DirDown) = p()
                                        |   find(_ :: tl, dir) = find (tl, dir)
                
                                    in
                                        SOME(find(tree, direction))
                                    end
                            (* Update the last tree if it's still valid. *)
                            val () = updateLastParse(currentParseID, newTree)
                        in
                            treeLocation newTree (* Return the location of the updated tree. *)
                        end
                        else { startOffset = 0, endOffset = 0 } (* *)
                in
                    sendResponse(
                        MoveResponse {
                            requestId = requestId, parseTreeId = currentParseID, location = newLocation
                        });
                    runProtocol currentCompilation
                end

            |   TypeRequest { requestId, parseTreeId, location } =>
                let (* Type of value at selected node. *)
                    val (_, lastParsetree, currentParseID) = getCurrentParse()
                    val (typeRes, location) =
                        if parseTreeId = currentParseID
                        then
                        let
                            (* Move to the required location. *)
                            val newTree = navigateTo(location, lastParsetree)
                            val () = updateLastParse(currentParseID, newTree)
                            (* If it has a type return it. *)
                            val typeRes =
                                case newTree of
                                    NONE => NONE
                                |   (SOME(_, tree)) =>
                                    (
                                        (* Print the type if it's there.  Don't include any mark-up. *)
                                        (* TODO: This uses the global name space to find types and structures.
                                           It really should use the local name space but that requires adding
                                           an environment to the parse tree. *)
                                        case List.find (fn (PolyML.PTtype _) => true | _ => false) tree of
                                            SOME(PolyML.PTtype t) =>
                                                SOME(PolyML.NameSpace.Values.printType(t, 100, SOME PolyML.globalNameSpace))
                                        |   _ => NONE
                                    )
                        in
                           (typeRes, treeLocation newTree)
                        end
                        else (NONE, { startOffset = 0, endOffset = 0 })
                in
                    sendResponse(
                        TypeResponse {
                            requestId = requestId, parseTreeId = currentParseID,
                            location = location, typeRes = typeRes
                        });
                    runProtocol currentCompilation
                end

            |   DecRequest { requestId, parseTreeId, location, decType } =>
                let (* Information about declaration location of identifier at selected node. *)
                    val (_, lastParsetree, currentParseID) = getCurrentParse()
                    val (decLocation, location) =
                        if parseTreeId = currentParseID
                        then
                        let
                            (* Move to the required location. *)
                            val newTree = navigateTo(location, lastParsetree)
                            val () = updateLastParse(currentParseID, newTree)
                            val decLocation =
                                (* If it has the right kind of property return it. *)
                                case newTree of
                                    NONE => NONE
                                |   (SOME(_, tree)) =>
                                    let
                                        open PolyML
                                        val getLoc =
                                            case decType of
                                                DecLocal => (fn (PTdeclaredAt p) => SOME p | _ => NONE)
                                            |   DecOpen => (fn (PTopenedAt p) => SOME p | _ => NONE)
                                            |   DecParent => (fn (PTstructureAt p) => SOME p | _ => NONE)
                                        (* Seatch in the properties of the current node for the property we want. *)
                                        fun findLoc [] = NONE
                                        |   findLoc (hd::tl) =
                                            case getLoc hd of
                                                SOME location => SOME location
                                            |   NONE => (* Keep trying. *) findLoc tl
                                    in
                                        findLoc tree
                                    end
                        in
                            (decLocation, treeLocation newTree)
                        end
                        else (NONE, { startOffset = 0, endOffset = 0 })
                in
                    sendResponse(
                        DecResponse {
                            requestId = requestId, parseTreeId = currentParseID,
                            location = location, decLocation = decLocation
                        });
                    runProtocol currentCompilation
                end

            |   RefRequest { requestId, parseTreeId, location } =>
                let (* Type of value at selected node. *)
                    val (_, lastParsetree, currentParseID) = getCurrentParse()
                    val (references, location) =
                        if parseTreeId = currentParseID
                        then
                        let
                            (* Move to the required location. *)
                            val newTree = navigateTo(location, lastParsetree)
                            val () = updateLastParse(currentParseID, newTree)
                            (* Find the local references. *)
                            val references =
                                case newTree of
                                    NONE => []
                                |   SOME(_, tree) =>
                                    (
                                        case List.find (fn (PolyML.PTreferences _) => true | _ => false) tree of
                                            SOME(PolyML.PTreferences(_, l)) =>
                                                List.map (fn {startPosition, endPosition, ...} =>
                                                            { startOffset=startPosition, endOffset=endPosition}) l
                                        |   _ => []
                                    )
                        in
                           (references, treeLocation newTree)
                        end
                        else ([], { startOffset = 0, endOffset = 0 })
                in
                    sendResponse(
                        RefResponse {
                            requestId = requestId, parseTreeId = currentParseID,
                            location = location, references = references
                        });
                    runProtocol currentCompilation
                end

            |   CompileRequest { requestId, fileName, startPosition, preludeCode, sourceCode } =>
                (* Unlike the other requests this is done asynchronously. *)
                let
                    fun compileThread () =
                    let
                        type errorMsg =
                            { message: PolyML.pretty, hard: bool, location: PolyML.location,
                              context: PolyML.pretty option }
                        (* Even success may include warning messages. *)
                        datatype compileResult =
                            Success
                        |   Exception of exn
                        |   Interrupted
                        |   Errors

                        local
                            open PolyML.NameSpace
                            (* Put in the results without printing. *)
                            fun resultFun
                                { fixes: (string * Infixes.fixity) list, values: (string * Values.value) list,
                                  structures: (string * Structures.structureVal) list, signatures: (string * Signatures.signatureVal) list,
                                  functors: (string * Functors.functorVal) list, types: (string * TypeConstrs.typeConstr) list} =
                            let
                                open PolyML
                            in
                                List.app (#enterFix globalNameSpace) fixes;
                                List.app (#enterType globalNameSpace) types;
                                List.app (#enterSig globalNameSpace) signatures;
                                List.app (#enterStruct globalNameSpace) structures;
                                List.app (#enterFunct globalNameSpace) functors;
                                List.app (#enterVal globalNameSpace) values
                            end
                        in
                            (* Compile the prelude.  Simply returns true if it succeeded and false on any error.
                               Note: Unlike the main compilation this is run with the interlock held and
                               interrupts deferred. *)
                            fun compilePreludeString stringInput: string option =
                            let
                                val stringStream = TextIO.openString stringInput

                                fun compilerResultFun (_, codeOpt) =
                                    case codeOpt of
                                        SOME code => (fn () => resultFun(code()))
                                     |  NONE => raise Fail "Static Errors"

                                fun compilerLoop () =
                                (* Compile each "program" until either we get to the end or an exception. *)
                                if TextIO.endOfStream stringStream
                                then NONE (* Reached the end of the input without error. *)
                                else 
                                let
                                    (* Compile the code and get the result. *)
                                    open PolyML PolyML.Compiler
                                    val (code, result) =
                                        (PolyML.compiler(fn () => TextIO.input1 stringStream,
                                            [CPOutStream TextIO.print, CPCompilerResultFun compilerResultFun]),
                                         NONE)
                                         handle exn => (fn() => (), SOME(exnMessage exn))
                                 in
                                    case result of
                                        NONE =>
                                        (
                                            (* No exception in compiler: run the code and check that it
                                               runs successfully. *)
                                            case ((code(); NONE) handle exn => SOME(exnMessage exn)) of
                                                NONE => compilerLoop () (* Continue. *)
                                            |   exn => exn
                                        )
                                    |   error => error
                                end
                                
                                fun runloop () =
                                let
                                    val res = compilerLoop()
                                in
                                    (* The prelude may update the current parse tree. *)
                                    case !parseTree of
                                        (_, []) => lastParsetree := NONE
                                    |   (_, hd :: _) => lastParsetree := SOME hd;
                                    res
                                end
                            in
                                (* This is run with the lock held. *)
                                withLock runloop
                            end

                            (* Compile the main source code. *)
                            fun compileString(stringInput, startPosition: int) =
                            let
                                val errorList = ref []
                                val stringPosition = ref 0
                                val stringSize = String.size stringInput
                                val resultTrees : PolyML.parseTree list ref = ref []
                                val lastTreePosition = ref 0
                                fun readIn () =
                                let
                                    val posn = ! stringPosition
                                in
                                    if posn >= stringSize
                                    then NONE
                                    else SOME(String.sub(stringInput, posn)) before (stringPosition := posn+1)
                                end
                                (* We need to define our own compilerResultFun in order to capture the parse trees. *)
                                fun compilerResultFun (parsetree, codeOpt) =
                                (
                                    (* Add the parsetree to the list.  Record this as the position of the last valid tree. *)
                                    case parsetree of
                                        SOME pt =>
                                            (resultTrees := ! resultTrees @ [pt]; lastTreePosition := !stringPosition)
                                    |   NONE => (); (* Not if parse failed. *)
                                    case codeOpt of
                                        SOME code => (fn () => resultFun(code()))
                                     |  NONE => raise Fail "Static Errors"
                                )

                                fun compilerLoop () =
                                (* Compile each "program" until either we get to the end or an exception. *)
                                if ! stringPosition >= stringSize
                                then Success (* Reached the end of the input without error. *)
                                else
                                let
                                    open PolyML PolyML.Compiler
                                    val (code, result) =
                                        (PolyML.compiler(readIn,
                                            [CPOutStream TextIO.print, CPLineOffset (fn () => startPosition + !stringPosition),
                                             CPErrorMessageProc (fn msg => errorList := !errorList @ [msg]),
                                             CPCompilerResultFun compilerResultFun, CPFileName fileName,
                                             CPRootTree (toplevelParseTree resultTrees)]),
                                         Success)
                                         handle Fail _ => (fn() => (), Errors)
                                         |  _ (* E.g. Interrupted *) => (fn() => (), Interrupted)
                                in
                                    case result of
                                        Success => (* Compilation succeeded. *)
                                        (
                                            (* Run the code.  If it raised an exception pass that back. *)
                                            case (code(); Success) handle exn => Exception exn of
                                                Success => compilerLoop () (* Continue. *)
                                            |   fault => fault
                                        )
                                    |   error => error
                                end
                            in
                                (compilerLoop (), startPosition + !lastTreePosition,
                                 ! resultTrees, ! errorList)
                            end
                        end
                    in
                        if
                        (* First run the prelude.  If there are any errors report them and stop. *)
                            case compilePreludeString preludeCode of
                                NONE => true (* Succeeded - continue *)
                            |   SOME preludeError =>  (* Error - stop *)
                                let
                                    (* Leave the parse tree unchanged. *)
                                    val (_, _, currentId) = getCurrentParse()
                                in
                                    sendResponse(
                                        CompilerResponse {
                                            requestId = requestId, parseTreeId = currentId,
                                            finalOffset = startPosition, result = PreludeFail preludeError
                                        });
                                    false
                                end
                        then (* We can do the main compilation. *)
                        let
                            local
                                open Thread.Thread
                            in
                                (* The rest of this code is interruptible
                                   TODO: Multiple interrupts could result in not sending a
                                   result packet. *)
                                val () =
                                    setAttributes [EnableBroadcastInterrupt true, InterruptState InterruptAsynch]
                            end;
                            val (result, finalPosition, resultTrees, errors) =
                                compileString(sourceCode, FixedInt.toInt startPosition)
                            fun makeErrorPacket
                                {message: PolyML.pretty, hard: bool, location, ...} =
                                {
                                    hardError = hard,
                                    location = location,
                                    message = message
                                }
                            val errorPackets = List.map makeErrorPacket errors
                            val compileResult  =
                                case result of
                                    Success => Succeeded errorPackets (* May be warning messages. *)
                                |   Exception exn =>
                                    let
                                        open PolyML
                                        val exLoc =
                                            case exceptionLocation exn of
                                                SOME loc => [ContextLocation loc]
                                            |   NONE => []
                                        val exceptionString =
                                            (PrettyBlock(0, false, exLoc,
                                                [ prettyRepresentation(exn, FixedInt.fromInt(!PolyML.Compiler.printDepth)) ]))
                                    in
                                        RuntimeException(exceptionString, errorPackets)
                                    end
                                |   Interrupted => CompileCancelled errorPackets
                                |   Errors => CompileFail errorPackets
                            (* Update the tree unless parsing failed and we don't have one. *)
                            val parseTreeId =
                                case resultTrees of
                                    [] => #3 (getCurrentParse()) (* Return existing tree. *)
                                |   _ => (setParseTree(resultTrees, requestId); requestId)
                        in
                            (* Send the response. *)
                            sendResponse(
                                CompilerResponse {
                                    requestId = requestId, parseTreeId = parseTreeId,
                                    finalOffset = FixedInt.fromInt finalPosition, result = compileResult
                                })
                        end
                        else () (* Prelude failed. *)
                    end (* compileThread *)

                    open Thread.Thread

                    (* First see if the last compilation has terminated.  Starting a new
                       compilation before the previous one has finished is really a
                       protocol error. *)
                    val isStillRunning =
                        case currentCompilation of
                            NONE => false
                        |   SOME (_, lastCompileThread) => isActive lastCompileThread
                in
                    if isStillRunning
                    then sendResponse(
                            CompilerResponse {
                                requestId = requestId, parseTreeId = #3 (getCurrentParse()),
                                finalOffset = startPosition, result = PreludeFail "Thread still running"
                            })
                    else
                    let
                        (* The compile thread is run with interrupts deferred initially. *)
                        val thread = fork(compileThread, [InterruptState InterruptDefer])
                    in
                        runProtocol (SOME(requestId, thread))
                    end
                end

            |   KillRequest { requestId: string } => (* Kill compilation. *)
                (
                    case currentCompilation of
                        NONE => () (* No compilation. *)
                    |   SOME (id, thread) =>
                        if requestId = id
                        then Thread.Thread.interrupt thread
                        else () (* Different ID running. *);
                    runProtocol currentCompilation
                )

            |   UnknownRequest req => (* Respond with an empty response. *)
                (
                    sendResponse(UnknownResponse req);
                    runProtocol currentCompilation
                )
        end
    in
        let
            (* Turn off interrupts for the interface thread. *)
            open Thread.Thread
        in
            setAttributes[EnableBroadcastInterrupt false, InterruptState InterruptDefer]
        end;
        sendStartedMessage(); 
        runProtocol NONE (* No compilation. *)
    end (* runIDEProtocol. *)

    local
        val polySpecificGeneralCall = RunCall.rtsCallFull2 "PolySpecificGeneral"
    in
        fun polySpecificGeneral(code: int, arg:'a):'b = RunCall.unsafeCast(polySpecificGeneralCall(RunCall.unsafeCast(code, arg)))
    end

in
    structure PolyML =
    struct
        (* This is the root function to run the Poly/ML top level. *)
        fun rootFunction () : unit =
        let
            val argList = CommandLine.arguments()
            fun rtsRelease() = polySpecificGeneral (10, ())
            fun rtsHelp() = polySpecificGeneral (19, ())
            val gitVersion =
                case polySpecificGeneral (9, ()) of
                   "" => ""
                |   s => " (Git version " ^ s ^ ")"
            
            fun switchOption option = List.exists(fn s => s = option) argList
        in
            if switchOption "-v"
            then (* -v option : Print version information and exit *)
                print (String.concat ["Poly/ML ", PolyML.Compiler.compilerVersion, 
                                     "    RTS version: ", rtsRelease(), gitVersion, "\n"])

            else if switchOption "--help"
            then (* --help option: Print argument information and exit. *)
               (
                print (String.concat ["Poly/ML ", PolyML.Compiler.compilerVersion, gitVersion, "\n"]);
                print "Compiler arguments:\n";
                print "\n";
                print "-v                   Print the version of Poly/ML and exit\n";
                print "--help               Print this message and exit\n";
                print "-q                   Suppress the start-up message and turn off printing of results\n";
                print "-i                   Interactive mode.  Default if input is from a terminal\n";
                print "--use FILE           Executes 'use \"FILE\";' before the ML shell starts\n";
                print "--eval STRING        Compiles and executes STRING as ML before the ML shell starts\n";
                print "--error-exit         Exit shell on unhandled exception\n";
                print "--with-markup        Include extra mark-up information when printing\n";
                print "--ideprotocol[=v2]   Run the IDE communications protocol\n";
                print "--script FILE        The input is a script.  Skips the first line if it begins with #!.";
                print "\nRun time system arguments:\n";
                print (rtsHelp())
               )

            else if switchOption "--ideprotocol"
            then runIDEProtocol () (* Run the IDE communication protocol. *)

            else if switchOption "--script"
            then
            let
                (* The next argument is the file name.  Open it but skip 
                   the first line if it's #!.   The rest of this code is
                   largely copied from PolyML.use.  *)
                fun getFileName("--script" :: fileName :: _) = fileName
                |   getFileName [] = (print "Missing file name after --script\n"; OS.Process.exit OS.Process.failure)
                |   getFileName(_ :: tail) = getFileName tail
                val fileName = getFileName argList
                open TextIO
                val inStream = getInstream(TextIO.openIn fileName)
                open StreamIO
                val stream = ref inStream

                val lineNo   = ref 1
                val (start, _) = inputN(inStream, 2)
                fun getChar () =
                    case input1 (! stream) of
                        NONE => NONE
                    |   SOME (eoln as #"\n", strm) =>
                        (
                            lineNo := !lineNo + 1;
                            stream := strm;
                            SOME eoln
                        )
                    |   SOME(c, strm) => (stream := strm; SOME c)
                val () =
                    if start = "#!"
                    then while (case getChar () of NONE => false | SOME #"\n" => false | SOME _ => true) do ()
                    else ()
                val () = PolyML.print_depth 0 (* Quieten. *)
            in
                while not (endOfStream(!stream)) do
                let
                    open PolyML.Compiler
                    val code = PolyML.compiler(getChar, [CPFileName fileName, CPLineNo(fn () => !lineNo)])
                        handle exn =>
                            ( closeIn(!stream); PolyML.Exception.reraise exn )
                in
                    code() handle exn =>
                    (
                        (* Report exceptions in running code. *)
                        TextIO.print ("Exception- " ^ exnMessage exn ^ " raised\n");
                        input1 (! stream);
                        PolyML.Exception.reraise exn
                    )
                end;
                (* Normal termination: close the stream. *)
                closeIn (! stream)
            end

            else (* Enter normal Poly/ML top-level. *)
            let
                open Signal
                val () =
                    if switchOption "-q"
                    then PolyML.print_depth 0
                    else print (String.concat ["Poly/ML ", PolyML.Compiler.compilerVersion, gitVersion, "\n"]);
                (* Set up a handler for SIGINT if that is currently set to SIG_DFL.
                   If a handler has been set up by an initialisation function don't replace it. *)
                val () =
                    case signal(2, SIG_IGN) of
                       SIG_IGN => ()
                    |  SIG_DFL => (signal(2, SIG_HANDLE(fn _ => Thread.Thread.broadcastInterrupt())); ())
                    |  oldHandle => (signal(2, oldHandle); ())

                fun tryUseFileArguments [] = () (* done successfully *)

                |   tryUseFileArguments ["--use"] =
                    (
                        print "'--use' requires a filename to be given as the next argument.\n";
                        OS.Process.exit OS.Process.failure
                    )

                |   tryUseFileArguments ("--use" :: filenameArg :: moreArgs) =
                    (
                        PolyML.use filenameArg
                            handle _ =>
                            (
                                print("Error trying to use the file: '" ^ filenameArg ^ "'\n");
                                OS.Process.exit OS.Process.failure
                            );
                        tryUseFileArguments moreArgs
                    )

                |   tryUseFileArguments ["--eval"] =
                    (
                        print "'--eval' requires a string to be given as the next argument.\n";
                        OS.Process.exit OS.Process.failure
                    )

                |   tryUseFileArguments ("--eval" :: useString :: moreArgs) =
                    let
                        (* Compile and execute commands from the string. *)
                        val p = ref 0
                    in
                        while !p < size useString do
                        let
                            fun getChar() =
                                if !p >= size useString
                                then NONE
                                else SOME(String.sub(useString, !p)) before p := !p+1
                            val code =
                                PolyML.compiler(getChar, [])
                                    handle _ => OS.Process.exit OS.Process.failure
                        in
                            code() handle exn =>
                            (
                                (* Report exceptions in running code. *)
                                print ("Exception- " ^ exnMessage exn ^ " raised\n");
                                OS.Process.exit OS.Process.failure
                            )
                        end;
                        tryUseFileArguments moreArgs
                    end

                |   tryUseFileArguments (_ :: args) = tryUseFileArguments args

            in
                tryUseFileArguments argList;
                PolyML.shell (); 
                OS.Process.exit OS.Process.success (* Run any "atExit" functions and then quit. *)
            end
        end;

        structure IDEInterface =
        struct
            val parseTree = parseTree
            val runIDEProtocol = runIDEProtocol
        end;

        open PolyML (* Add this to the PolyML structure. *)
    end
end;