/
TopLevelPolyML.sml
1728 lines (1610 loc) · 93.7 KB
/
TopLevelPolyML.sml
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
(*
Title: Root function for the PolyML structure
Author: David Matthews
Copyright David Matthews 2009, 2015
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: int, endOffset: 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: 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: 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 : int =
case Int.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, preludeLength)
val _ = readToEscape("", #",") (* Should be empty - check? *)
val sourceText = TextIO.inputN(inStream, 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[Int.toString startOffset, "\u001b,", Int.toString endOffset])
and printFullLocation { file, startLine, startPosition, endPosition, ...} =
(
print file; (* TODO double any escapes. *) printEsc #",";
print (Int.toString startLine); printEsc #",";
print (Int.toString startPosition); printEsc #",";
print (Int.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 (Int.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 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 startLine])
val encStart =
if startPosition = 0 then [] else encodeItem(Context(3, Primitive), [encodeInt startPosition])
val encEnd =
if endPosition = 0 then [] else encodeItem(Context(4, Primitive), [encodeInt endPosition])
in
encFile @ encLine @ encStart @ encEnd
end
and encodeLocation {startOffset, endOffset } =
encodeItem(Context(3, Primitive), [encodeInt startOffset]) @
encodeItem(Context(4, Primitive), [encodeInt 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 finalOffset]) @
encodeItem(Context(2, Primitive), [encodeInt 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)