-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLspHandlers.fs
More file actions
1329 lines (1203 loc) · 62.6 KB
/
LspHandlers.fs
File metadata and controls
1329 lines (1203 loc) · 62.6 KB
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
namespace FScript.LanguageServer
open System
open System.IO
open System.Text.Json.Nodes
open FScript.Language
open FScript.CSharpInterop
module LspHandlers =
open LspModel
open LspSymbols
let handleInitialize (idNode: JsonNode) (paramsObj: JsonObject option) =
match paramsObj with
| Some p ->
match tryGetObject p "initializationOptions" with
| Some init ->
match init["inlayHintsEnabled"] with
| :? JsonValue as v ->
try inlayHintsEnabled <- v.GetValue<bool>() with _ -> ()
| _ -> ()
| None -> ()
| None -> ()
let sync = JsonObject()
sync["openClose"] <- JsonValue.Create(true)
sync["change"] <- JsonValue.Create(1)
let completionProvider = JsonObject()
completionProvider["resolveProvider"] <- JsonValue.Create(false)
let triggerChars = JsonArray()
triggerChars.Add(JsonValue.Create("."))
triggerChars.Add(JsonValue.Create("["))
completionProvider["triggerCharacters"] <- triggerChars
let serverInfo = JsonObject()
serverInfo["name"] <- JsonValue.Create("FScript Language Server")
let capabilities = JsonObject()
capabilities["textDocumentSync"] <- sync
capabilities["completionProvider"] <- completionProvider
capabilities["hoverProvider"] <- JsonValue.Create(true)
capabilities["definitionProvider"] <- JsonValue.Create(true)
capabilities["typeDefinitionProvider"] <- JsonValue.Create(true)
capabilities["referencesProvider"] <- JsonValue.Create(true)
capabilities["documentHighlightProvider"] <- JsonValue.Create(true)
let renameProvider = JsonObject()
renameProvider["prepareProvider"] <- JsonValue.Create(true)
capabilities["renameProvider"] <- renameProvider
let signatureHelpProvider = JsonObject()
let signatureTriggers = JsonArray()
signatureTriggers.Add(JsonValue.Create("("))
signatureTriggers.Add(JsonValue.Create(","))
signatureHelpProvider["triggerCharacters"] <- signatureTriggers
capabilities["signatureHelpProvider"] <- signatureHelpProvider
capabilities["documentSymbolProvider"] <- JsonValue.Create(true)
capabilities["workspaceSymbolProvider"] <- JsonValue.Create(true)
capabilities["codeActionProvider"] <- JsonValue.Create(true)
capabilities["inlayHintProvider"] <- JsonValue.Create(true)
let semanticLegend = JsonObject()
let tokenTypeNodes = JsonArray()
[| "keyword"; "string"; "number"; "function"; "type"; "variable" |]
|> Array.iter (fun s -> tokenTypeNodes.Add(JsonValue.Create(s)))
semanticLegend["tokenTypes"] <- tokenTypeNodes
semanticLegend["tokenModifiers"] <- JsonArray()
let semanticProvider = JsonObject()
semanticProvider["legend"] <- semanticLegend
semanticProvider["full"] <- JsonValue.Create(true)
capabilities["semanticTokensProvider"] <- semanticProvider
let result = JsonObject()
result["capabilities"] <- capabilities
result["serverInfo"] <- serverInfo
LspProtocol.sendResponse idNode (Some result)
let private keywordSet =
[ "let"; "rec"; "and"; "if"; "then"; "elif"; "else"; "match"; "with"; "when"
"for"; "in"; "do"; "type"; "module"; "true"; "false"; "None"; "Some"
"fun"; "raise"; "import"; "export"; "qualified" ]
|> Set.ofList
let private classifyToken (line: string) (startIndex: int) (token: string) =
let isFunctionCallToken () =
let mutable i = startIndex + token.Length
while i < line.Length && Char.IsWhiteSpace(line[i]) do
i <- i + 1
i < line.Length && line[i] = '('
if keywordSet.Contains(token) then 0
elif token.Length > 1 && token.StartsWith("\"") && token.EndsWith("\"") then 1
elif token |> Seq.forall Char.IsDigit then 2
elif isFunctionCallToken () then 3
elif token.Contains('.') then
let tail = token.Split('.') |> Array.last
if tail.Length > 0 && Char.IsLower(tail[0]) then 3 else 4
elif token.Length > 0 && Char.IsUpper(token[0]) then 4
else 5
let private scanSemanticTokens (text: string) =
let lines = text.Split('\n')
let mutable previousLine = 0
let mutable previousStart = 0
let data = ResizeArray<int>()
for lineIndex = 0 to lines.Length - 1 do
let line = lines[lineIndex].TrimEnd('\r')
let mutable i = 0
while i < line.Length do
let c = line[i]
if Char.IsWhiteSpace(c) then
i <- i + 1
elif c = '/' && i + 1 < line.Length && line[i + 1] = '/' then
i <- line.Length
elif c = '"' then
let start = i
i <- i + 1
while i < line.Length && line[i] <> '"' do
i <- i + 1
if i < line.Length then i <- i + 1
let length = i - start
let deltaLine = lineIndex - previousLine
let deltaStart = if deltaLine = 0 then start - previousStart else start
data.Add(deltaLine)
data.Add(deltaStart)
data.Add(length)
data.Add(1)
data.Add(0)
previousLine <- lineIndex
previousStart <- start
elif Char.IsLetter(c) || c = '_' then
let start = i
i <- i + 1
while i < line.Length && (Char.IsLetterOrDigit(line[i]) || line[i] = '_' || line[i] = '.') do
i <- i + 1
let token = line.Substring(start, i - start)
let tokenType = classifyToken line start token
let deltaLine = lineIndex - previousLine
let deltaStart = if deltaLine = 0 then start - previousStart else start
data.Add(deltaLine)
data.Add(deltaStart)
data.Add(token.Length)
data.Add(tokenType)
data.Add(0)
previousLine <- lineIndex
previousStart <- start
elif Char.IsDigit(c) then
let start = i
i <- i + 1
while i < line.Length && (Char.IsDigit(line[i]) || line[i] = '.') do
i <- i + 1
let length = i - start
let deltaLine = lineIndex - previousLine
let deltaStart = if deltaLine = 0 then start - previousStart else start
data.Add(deltaLine)
data.Add(deltaStart)
data.Add(length)
data.Add(2)
data.Add(0)
previousLine <- lineIndex
previousStart <- start
else
i <- i + 1
data
let handleSemanticTokens (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj with
| Some uri when documents.ContainsKey(uri) ->
let doc = documents[uri]
let data: JsonNode array =
scanSemanticTokens doc.Text
|> Seq.map (fun n -> JsonValue.Create(n) :> JsonNode)
|> Seq.toArray
let result = JsonObject()
result["data"] <- JsonArray(data)
LspProtocol.sendResponse idNode (Some result)
| _ ->
let result = JsonObject()
result["data"] <- JsonArray()
LspProtocol.sendResponse idNode (Some result)
let private positionInRange (line: int) (character: int) (sl: int, sc: int, el: int, ec: int) =
let afterStart = line > sl || (line = sl && character >= sc)
let beforeEnd = line < el || (line = el && character <= ec)
afterStart && beforeEnd
let private trimOuterParens (text: string) =
let rec trim (value: string) =
let trimmed = value.Trim()
if trimmed.Length >= 2 && trimmed[0] = '(' && trimmed[trimmed.Length - 1] = ')' then
let mutable depth = 0
let mutable enclosesAll = true
let mutable i = 0
while i < trimmed.Length && enclosesAll do
let c = trimmed[i]
if c = '(' then depth <- depth + 1
elif c = ')' then
depth <- depth - 1
if depth = 0 && i < trimmed.Length - 1 then
enclosesAll <- false
i <- i + 1
if enclosesAll then trim (trimmed.Substring(1, trimmed.Length - 2))
else trimmed
else
trimmed
trim text
let private splitTopLevelArrows (typeText: string) =
let typeText = trimOuterParens typeText
let parts = ResizeArray<string>()
let mutable depthParen = 0
let mutable depthBrace = 0
let mutable depthBracket = 0
let mutable start = 0
let mutable i = 0
while i < typeText.Length do
let c = typeText[i]
match c with
| '(' -> depthParen <- depthParen + 1
| ')' when depthParen > 0 -> depthParen <- depthParen - 1
| '{' -> depthBrace <- depthBrace + 1
| '}' when depthBrace > 0 -> depthBrace <- depthBrace - 1
| '[' -> depthBracket <- depthBracket + 1
| ']' when depthBracket > 0 -> depthBracket <- depthBracket - 1
| '-' when i + 1 < typeText.Length && typeText[i + 1] = '>' && depthParen = 0 && depthBrace = 0 && depthBracket = 0 ->
let chunk = typeText.Substring(start, i - start).Trim()
if chunk <> "" then
parts.Add(chunk)
i <- i + 1
start <- i + 1
| _ -> ()
i <- i + 1
if start <= typeText.Length then
let tail = typeText.Substring(start).Trim()
if tail <> "" then
parts.Add(tail)
parts |> Seq.toList
let private flattenArrowParts (typeText: string) =
let rec flatten (text: string) =
let parts = splitTopLevelArrows text
match parts with
| [] -> []
| [ single ] ->
let trimmed = trimOuterParens single
if String.Equals(trimmed, single, StringComparison.Ordinal) then
[ trimmed ]
else
flatten trimmed
| first :: rest when rest.Length = 1 ->
first :: flatten rest[0]
| _ ->
parts
flatten typeText
let private formatNamedArrowSignature (names: string list) (typeText: string) =
let parts = flattenArrowParts typeText
if parts.Length = (names.Length + 1) then
let args =
[ 0 .. names.Length - 1 ]
|> List.map (fun i -> $"({names[i]}: {parts[i]})")
String.concat " -> " (args @ [ parts[parts.Length - 1] ])
else
typeText
let private formatFunctionSignature (doc: DocumentState) (sym: TopLevelSymbol) =
let paramNames = doc.FunctionParameters |> Map.tryFind sym.Name |> Option.defaultValue []
match sym.TypeText with
| Some typeText when sym.Kind = 12 && not paramNames.IsEmpty ->
let parts = flattenArrowParts typeText
if parts.Length = (paramNames.Length + 1) then
let effectiveParts =
match sym.TypeTargetName with
| Some returnName when parts.Length > 0 ->
(parts |> List.take (parts.Length - 1)) @ [ returnName ]
| _ -> parts
let arrowText =
if effectiveParts.Length = (paramNames.Length + 1) then
let args =
[ 0 .. paramNames.Length - 1 ]
|> List.map (fun i -> $"({paramNames[i]}: {effectiveParts[i]})")
String.concat " -> " (args @ [ effectiveParts[effectiveParts.Length - 1] ])
else
String.concat " -> " effectiveParts
$"{sym.Name}: {arrowText}"
else
$"{sym.Name} : {typeText}"
| Some typeText ->
$"{sym.Name} : {typeText}"
| None when sym.Kind = 12 && not paramNames.IsEmpty ->
match doc.FunctionAnnotationTypes |> Map.tryFind sym.Name with
| Some annotated when annotated.Length = paramNames.Length ->
let returnType =
doc.FunctionDeclaredReturnTargets
|> Map.tryFind sym.Name
|> Option.defaultValue "unknown"
let parts = annotated @ [ returnType ]
let arrowText =
if parts.Length = (paramNames.Length + 1) then
let args =
[ 0 .. paramNames.Length - 1 ]
|> List.map (fun i -> $"({paramNames[i]}: {parts[i]})")
String.concat " -> " (args @ [ parts[parts.Length - 1] ])
else
String.concat " -> " parts
$"{sym.Name}: {arrowText}"
| _ ->
let args = paramNames |> List.map (fun name -> $"({name})") |> String.concat " "
$"{sym.Name} {args}"
| None ->
sym.Name
let private formatInjectedFunctionSignature (doc: DocumentState) (name: string) (typeText: string) =
match doc.InjectedFunctionParameterNames |> Map.tryFind name with
| Some parameterNames when not parameterNames.IsEmpty ->
let namedSignature = formatNamedArrowSignature parameterNames typeText
$"{name}: {namedSignature}"
| _ ->
$"{name} : {typeText}"
let handleInlayHints (idNode: JsonNode) (paramsObj: JsonObject) =
if not inlayHintsEnabled then
LspProtocol.sendResponse idNode (Some (JsonArray()))
else
match tryGetUriFromTextDocument paramsObj with
| Some uri when documents.ContainsKey(uri) ->
let doc = documents[uri]
let (startLine, startChar, endLine, endChar) =
tryGetRange paramsObj |> Option.defaultValue (0, 0, Int32.MaxValue, Int32.MaxValue)
let hints = ResizeArray<JsonNode>()
// Type hints for value bindings based on inferred top-level symbol types.
doc.Symbols
|> List.iter (fun sym ->
if sym.Kind = 13 && not (sym.Name.Contains('.')) then
match sym.TypeText with
| Some typeText ->
let hintLine = max 0 (sym.Span.End.Line - 1)
let hintChar = max 0 (sym.Span.End.Column - 1)
if positionInRange hintLine hintChar (startLine, startChar, endLine, endChar) then
let hint = JsonObject()
let pos = JsonObject()
pos["line"] <- JsonValue.Create(hintLine)
pos["character"] <- JsonValue.Create(hintChar)
hint["position"] <- pos
hint["label"] <- JsonValue.Create($": {typeText}")
hint["kind"] <- JsonValue.Create(1)
hint["paddingLeft"] <- JsonValue.Create(true)
hints.Add(hint :> JsonNode)
| None -> ())
// Type hints for function/lambda parameters inferred by the typechecker.
doc.ParameterTypeHints
|> List.iter (fun (span, label) ->
let hintLine = max 0 (span.End.Line - 1)
let hintChar = max 0 (span.End.Column - 1)
if positionInRange hintLine hintChar (startLine, startChar, endLine, endChar) then
let hint = JsonObject()
let pos = JsonObject()
pos["line"] <- JsonValue.Create(hintLine)
pos["character"] <- JsonValue.Create(hintChar)
hint["position"] <- pos
hint["label"] <- JsonValue.Create(label)
hint["kind"] <- JsonValue.Create(1)
hint["paddingLeft"] <- JsonValue.Create(true)
hints.Add(hint :> JsonNode))
// Return type hints for function declarations.
doc.FunctionReturnTypeHints
|> List.iter (fun (span, label) ->
let hintLine = max 0 (span.End.Line - 1)
let hintChar = max 0 (span.End.Column - 1)
if positionInRange hintLine hintChar (startLine, startChar, endLine, endChar) then
let hint = JsonObject()
let pos = JsonObject()
pos["line"] <- JsonValue.Create(hintLine)
pos["character"] <- JsonValue.Create(hintChar)
hint["position"] <- pos
hint["label"] <- JsonValue.Create(label)
hint["kind"] <- JsonValue.Create(1)
hint["paddingLeft"] <- JsonValue.Create(true)
hints.Add(hint :> JsonNode))
// Type hints for pattern-bound variables (for example: `Some x`).
doc.PatternTypeHints
|> List.iter (fun (span, label) ->
let hintLine = max 0 (span.End.Line - 1)
let hintChar = max 0 (span.End.Column - 1)
if positionInRange hintLine hintChar (startLine, startChar, endLine, endChar) then
let hint = JsonObject()
let pos = JsonObject()
pos["line"] <- JsonValue.Create(hintLine)
pos["character"] <- JsonValue.Create(hintChar)
hint["position"] <- pos
hint["label"] <- JsonValue.Create(label)
hint["kind"] <- JsonValue.Create(1)
hint["paddingLeft"] <- JsonValue.Create(true)
hints.Add(hint :> JsonNode))
doc.CallArgumentHints
|> List.iter (fun (span, label) ->
let hintLine = max 0 (span.Start.Line - 1)
let hintChar = max 0 (span.Start.Column - 1)
if positionInRange hintLine hintChar (startLine, startChar, endLine, endChar) then
let hint = JsonObject()
let pos = JsonObject()
pos["line"] <- JsonValue.Create(hintLine)
pos["character"] <- JsonValue.Create(hintChar)
hint["position"] <- pos
hint["label"] <- JsonValue.Create(label)
hint["kind"] <- JsonValue.Create(2)
hint["paddingRight"] <- JsonValue.Create(true)
hints.Add(hint :> JsonNode))
LspProtocol.sendResponse idNode (Some (JsonArray(hints.ToArray())))
| _ ->
LspProtocol.sendResponse idNode (Some (JsonArray()))
let handleDidOpen (paramsObj: JsonObject) =
match tryGetObject paramsObj "textDocument" with
| Some textDocument ->
match tryGetString textDocument "uri", tryGetString textDocument "text" with
| Some uri, Some text -> analyzeDocument uri text
| _ -> ()
| None -> ()
let handleDidChange (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj with
| None -> ()
| Some uri ->
match paramsObj["contentChanges"] with
| :? JsonArray as changes ->
let mutable latest: string option = None
for change in changes do
match change with
| :? JsonObject as changeObj ->
match tryGetString changeObj "text" with
| Some text -> latest <- Some text
| None -> ()
| _ -> ()
match latest with
| Some text -> analyzeDocument uri text
| None -> ()
| _ -> ()
let handleDidClose (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj with
| Some uri ->
documents.Remove(uri) |> ignore
publishDiagnostics uri []
| None -> ()
let private tryGetCommandUri (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj with
| Some uri -> Some uri
| None -> tryGetString paramsObj "uri"
let private sendCommandError (idNode: JsonNode) (kind: string) (message: string) =
let errorObj = JsonObject()
errorObj["message"] <- JsonValue.Create(message)
errorObj["kind"] <- JsonValue.Create(kind)
let response = JsonObject()
response["ok"] <- JsonValue.Create(false)
response["error"] <- errorObj
LspProtocol.sendResponse idNode (Some response)
let private tryLoadSourceForUri (uri: string) =
if documents.ContainsKey(uri) then
Some documents[uri].Text
else
try
let filePath = Uri(uri).LocalPath
if File.Exists(filePath) then
Some (File.ReadAllText(filePath))
else
None
with _ ->
None
let handleViewAst (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetCommandUri paramsObj with
| None ->
sendCommandError idNode "internal" "Missing document URI."
| Some uri ->
try
let uriObj = Uri(uri)
if not (String.Equals(uriObj.Scheme, "file", StringComparison.OrdinalIgnoreCase)) then
sendCommandError idNode "internal" "AST commands support file-based scripts only."
else
let sourcePath = uriObj.LocalPath
match tryLoadSourceForUri uri with
| None ->
sendCommandError idNode "internal" $"Unable to read source file '{sourcePath}'."
| Some sourceText ->
let program = InteropServices.parseProgramFromSourceWithIncludes sourcePath sourceText
let response = JsonObject()
response["ok"] <- JsonValue.Create(true)
response["data"] <- AstJson.programToJson sourcePath program
LspProtocol.sendResponse idNode (Some response)
with
| :? ParseException as ex ->
sendCommandError idNode "parse" ex.Message
| ex ->
sendCommandError idNode "internal" ex.Message
let handleViewInferredAst (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetCommandUri paramsObj with
| None ->
sendCommandError idNode "internal" "Missing document URI."
| Some uri ->
try
let uriObj = Uri(uri)
if not (String.Equals(uriObj.Scheme, "file", StringComparison.OrdinalIgnoreCase)) then
sendCommandError idNode "internal" "AST commands support file-based scripts only."
else
let sourcePath = uriObj.LocalPath
match tryLoadSourceForUri uri with
| None ->
sendCommandError idNode "internal" $"Unable to read source file '{sourcePath}'."
| Some sourceText ->
let program = InteropServices.parseProgramFromSourceWithIncludes sourcePath sourceText
let runtimeExterns = LspRuntimeExterns.forSourcePath sourcePath
let typedProgram = InteropServices.inferProgramWithExterns runtimeExterns program
let response = JsonObject()
response["ok"] <- JsonValue.Create(true)
response["data"] <- AstJson.typedProgramToJson sourcePath typedProgram
LspProtocol.sendResponse idNode (Some response)
with
| :? ParseException as ex ->
sendCommandError idNode "parse" ex.Message
| :? TypeException as ex ->
sendCommandError idNode "type" ex.Message
| ex ->
sendCommandError idNode "internal" ex.Message
let handleHover (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj, tryGetPosition paramsObj with
| Some uri, Some (line, character) when documents.ContainsKey(uri) ->
let doc = documents[uri]
match tryGetRecordFieldHoverInfo doc line character with
| Some (fieldName, fieldType) ->
let contents = JsonObject()
contents["kind"] <- JsonValue.Create("markdown")
contents["value"] <- JsonValue.Create($"```fscript\n{fieldName} : {fieldType}\n```\nrecord-field")
let result = JsonObject()
result["contents"] <- contents
LspProtocol.sendResponse idNode (Some result)
| None ->
match tryGetLocalVariableHoverInfo doc line character with
| Some (name, typeText) ->
let contents = JsonObject()
contents["kind"] <- JsonValue.Create("markdown")
contents["value"] <- JsonValue.Create($"```fscript\n{name} : {typeText}\n```\nlocal-variable")
let result = JsonObject()
result["contents"] <- contents
LspProtocol.sendResponse idNode (Some result)
| None ->
match tryResolveSymbol doc line character with
| Some sym ->
let signature = formatFunctionSignature doc sym
let contents = JsonObject()
contents["kind"] <- JsonValue.Create("markdown")
let kindLine = symbolKindLabel sym.Kind
let locationLine = $"defined at L{sym.Span.Start.Line}:C{sym.Span.Start.Column}"
contents["value"] <- JsonValue.Create($"```fscript\n{signature}\n```\n{kindLine}\n\n{locationLine}")
let result = JsonObject()
result["contents"] <- contents
LspProtocol.sendResponse idNode (Some result)
| None ->
match tryGetWordAtPosition doc.Text line character with
| Some word ->
let candidates =
if word.Contains('.') then
[ word
word.Split('.') |> Array.last ]
else
[ word ]
let injectedMatch =
candidates
|> List.tryPick (fun candidate ->
doc.InjectedFunctionSignatures
|> Map.tryFind candidate
|> Option.map (fun t -> candidate, t))
match injectedMatch with
| Some (name, typeText) ->
let contents = JsonObject()
contents["kind"] <- JsonValue.Create("markdown")
let signature = formatInjectedFunctionSignature doc name typeText
contents["value"] <- JsonValue.Create($"```fscript\n{signature}\n```\ninjected-function")
let result = JsonObject()
result["contents"] <- contents
LspProtocol.sendResponse idNode (Some result)
| None ->
LspProtocol.sendResponse idNode None
| None ->
LspProtocol.sendResponse idNode None
| _ -> LspProtocol.sendResponse idNode None
let private tryResolveIncludeLocation (sourceUri: string) (doc: DocumentState) (line: int) (character: int) : JsonObject option =
match getLineText doc.Text line with
| None -> None
| Some lineText ->
let trimmed = lineText.TrimStart()
if not (trimmed.StartsWith("import", StringComparison.Ordinal)) then
None
else
let firstQuote = lineText.IndexOf('"')
if firstQuote < 0 then None
else
let secondQuote = lineText.IndexOf('"', firstQuote + 1)
if secondQuote <= firstQuote then None
else
let insideLiteral = character >= (firstQuote + 1) && character <= secondQuote
if not insideLiteral then
None
else
let includePath = lineText.Substring(firstQuote + 1, secondQuote - firstQuote - 1)
if String.IsNullOrWhiteSpace(includePath) then
None
else
try
let fullPath =
if Path.IsPathRooted(includePath) then
Path.GetFullPath(includePath)
else
if sourceUri.StartsWith("file://", StringComparison.OrdinalIgnoreCase) then
let sourcePath = Uri(sourceUri).LocalPath
match Path.GetDirectoryName(sourcePath) with
| null -> Path.GetFullPath(includePath)
| baseDir when String.IsNullOrWhiteSpace(baseDir) -> Path.GetFullPath(includePath)
| baseDir -> Path.GetFullPath(Path.Combine(baseDir, includePath))
else
includePath
if File.Exists(fullPath) then
let loc = JsonObject()
loc["uri"] <- JsonValue.Create(Uri(fullPath).AbsoluteUri)
let startPos = Span.pos 1 1
loc["range"] <- toLspRange (Span.mk startPos startPos)
Some loc
else
None
with _ ->
None
let private tryUriFromSpanFile (fallbackUri: string) (span: Span) =
match span.Start.File with
| Some filePath when not (String.IsNullOrWhiteSpace(filePath)) ->
try Some (Uri(filePath).AbsoluteUri) with _ -> Some fallbackUri
| _ ->
Some fallbackUri
let handleDefinition (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj, tryGetPosition paramsObj with
| Some uri, Some (line, character) when documents.ContainsKey(uri) ->
let doc = documents[uri]
match tryResolveIncludeLocation uri doc line character with
| Some includeLoc ->
LspProtocol.sendResponse idNode (Some includeLoc)
| None ->
let localSymbol = tryResolveSymbol doc line character
let wordAtCursor = tryGetWordAtPosition doc.Text line character
let symbolAndUri =
match localSymbol with
| Some sym ->
match tryUriFromSpanFile uri sym.Span with
| Some targetUri -> Some (targetUri, sym)
| None -> Some (uri, sym)
| None ->
match wordAtCursor with
| Some word ->
documents
|> Seq.tryPick (fun kv ->
kv.Value.Symbols
|> List.tryFind (fun s -> s.Name = word)
|> Option.map (fun s -> kv.Key, s))
| None -> None
match symbolAndUri with
| Some (targetUri, sym) ->
let loc = JsonObject()
loc["uri"] <- JsonValue.Create(targetUri)
loc["range"] <- toLspRange sym.Span
LspProtocol.sendResponse idNode (Some loc)
| None ->
let injectedDefinition =
match wordAtCursor with
| Some word ->
let candidates =
if word.Contains('.') then
[ word; word.Split('.') |> Array.last ]
else
[ word ]
candidates
|> List.tryPick (fun candidate ->
doc.InjectedFunctionDefinitions
|> Map.tryFind candidate
|> Option.map (fun target -> candidate, target))
| None ->
None
match injectedDefinition with
| Some (_, (targetUri, targetSpan)) ->
let loc = JsonObject()
loc["uri"] <- JsonValue.Create(targetUri)
loc["range"] <- toLspRange targetSpan
LspProtocol.sendResponse idNode (Some loc)
| None ->
match tryResolveTypeTargetAtPosition doc line character with
| Some typeName ->
match doc.Symbols |> List.tryFind (fun s -> s.Kind = 5 && s.Name = typeName) with
| Some typeSym ->
let loc = JsonObject()
let targetUri =
tryUriFromSpanFile uri typeSym.Span
|> Option.defaultValue uri
loc["uri"] <- JsonValue.Create(targetUri)
loc["range"] <- toLspRange typeSym.Span
LspProtocol.sendResponse idNode (Some loc)
| None ->
LspProtocol.sendResponse idNode None
| None ->
LspProtocol.sendResponse idNode None
| _ -> LspProtocol.sendResponse idNode None
let handleTypeDefinition (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj, tryGetPosition paramsObj with
| Some uri, Some (line, character) when documents.ContainsKey(uri) ->
let doc = documents[uri]
let targetTypeName =
match tryResolveSymbol doc line character with
| Some sym ->
match sym.TypeTargetName with
| Some name -> Some name
| None ->
sym.TypeText
|> Option.bind (fun t ->
doc.Symbols
|> List.tryFind (fun s -> s.Kind = 5 && s.Name = t)
|> Option.map (fun s -> s.Name))
| None ->
tryResolveTypeTargetAtPosition doc line character
match targetTypeName with
| Some typeName ->
match doc.Symbols |> List.tryFind (fun s -> s.Kind = 5 && s.Name = typeName) with
| Some typeSym ->
let loc = JsonObject()
let targetUri =
tryUriFromSpanFile uri typeSym.Span
|> Option.defaultValue uri
loc["uri"] <- JsonValue.Create(targetUri)
loc["range"] <- toLspRange typeSym.Span
LspProtocol.sendResponse idNode (Some loc)
| None ->
LspProtocol.sendResponse idNode None
| None ->
LspProtocol.sendResponse idNode None
| _ ->
LspProtocol.sendResponse idNode None
let handleCompletion (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj with
| Some uri when documents.ContainsKey(uri) ->
let doc = documents[uri]
let prefix =
match tryGetPosition paramsObj with
| Some (line, character) -> tryGetWordPrefixAtPosition doc.Text line character
| None -> None
let items = makeCompletionItems doc prefix
let result = JsonObject()
result["isIncomplete"] <- JsonValue.Create(false)
result["items"] <- items
LspProtocol.sendResponse idNode (Some result)
| _ ->
let result = JsonObject()
result["isIncomplete"] <- JsonValue.Create(false)
result["items"] <- JsonArray()
LspProtocol.sendResponse idNode (Some result)
let handleDocumentSymbol (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj with
| Some uri when documents.ContainsKey(uri) ->
let symbols =
documents[uri].Symbols
|> List.map (fun s ->
let d = JsonObject()
d["name"] <- JsonValue.Create(s.Name)
d["kind"] <- JsonValue.Create(s.Kind)
d["range"] <- toLspRange s.Span
d["selectionRange"] <- toLspRange s.Span
d)
let nodes = symbols |> List.map (fun s -> s :> JsonNode) |> List.toArray
LspProtocol.sendResponse idNode (Some (JsonArray(nodes)))
| _ -> LspProtocol.sendResponse idNode (Some (JsonArray()))
let private resolveTargetNames (doc: DocumentState) line character =
match tryResolveSymbol doc line character with
| Some sym ->
let normalized =
if sym.Name.Contains('.') then sym.Name.Split('.') |> Array.last
else sym.Name
[ sym.Name; normalized ]
| None ->
match tryGetWordAtPosition doc.Text line character with
| Some word ->
let normalized =
if word.Contains('.') then word.Split('.') |> Array.last
else word
[ word; normalized ]
| None -> []
let handleReferences (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj, tryGetPosition paramsObj with
| Some uri, Some (line, character) when documents.ContainsKey(uri) ->
let doc = documents[uri]
let targetNames = resolveTargetNames doc line character
let includeDeclaration =
match tryGetObject paramsObj "context" with
| Some contextObj ->
match contextObj["includeDeclaration"] with
| :? JsonValue as v ->
try v.GetValue<bool>() with _ -> true
| _ -> true
| None -> true
match targetNames with
| head :: _ ->
let normalized =
if head.Contains('.') then head.Split('.') |> Array.last
else head
let declarationSpansByUri =
documents
|> Seq.map (fun kv ->
let docUri = kv.Key
let spans =
kv.Value.Symbols
|> List.choose (fun s ->
let symbolNormalized =
if s.Name.Contains('.') then s.Name.Split('.') |> Array.last
else s.Name
if s.Name = head || s.Name = normalized || symbolNormalized = normalized then
Some s.Span
else
None)
|> Set.ofList
docUri, spans)
|> Map.ofSeq
let locations =
documents
|> Seq.collect (fun kv ->
let docUri = kv.Key
let candidateDoc = kv.Value
let fromOccurrences =
[ head; normalized ]
|> List.distinct
|> List.collect (fun n -> candidateDoc.VariableOccurrences |> Map.tryFind n |> Option.defaultValue [])
|> List.distinct
let spans =
if fromOccurrences.IsEmpty then
findSymbolRangesInText candidateDoc.Text (targetNames @ [ normalized ])
else
fromOccurrences
let filteredSpans =
if includeDeclaration then
spans
else
let decls = declarationSpansByUri |> Map.tryFind docUri |> Option.defaultValue Set.empty
spans |> List.filter (fun span -> not (decls.Contains span))
filteredSpans
|> List.map (fun span ->
let loc = JsonObject()
loc["uri"] <- JsonValue.Create(docUri)
loc["range"] <- toLspRange span
loc :> JsonNode))
|> Seq.toArray
LspProtocol.sendResponse idNode (Some (JsonArray(locations)))
| [] ->
LspProtocol.sendResponse idNode (Some (JsonArray()))
| _ ->
LspProtocol.sendResponse idNode (Some (JsonArray()))
let handleDocumentHighlight (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj, tryGetPosition paramsObj with
| Some uri, Some (line, character) when documents.ContainsKey(uri) ->
let doc = documents[uri]
let targetNames = resolveTargetNames doc line character
match targetNames with
| head :: _ ->
let normalized =
if head.Contains('.') then head.Split('.') |> Array.last
else head
let fromOccurrences =
[ head; normalized ]
|> List.distinct
|> List.collect (fun n -> doc.VariableOccurrences |> Map.tryFind n |> Option.defaultValue [])
|> List.distinct
let spans =
if fromOccurrences.IsEmpty then
findSymbolRangesInText doc.Text (targetNames @ [ normalized ])
else
fromOccurrences
let highlights =
spans
|> List.map (fun span ->
let highlight = JsonObject()
highlight["range"] <- toLspRange span
highlight["kind"] <- JsonValue.Create(1)
highlight :> JsonNode)
|> List.toArray
LspProtocol.sendResponse idNode (Some (JsonArray(highlights)))
| [] ->
LspProtocol.sendResponse idNode (Some (JsonArray()))
| _ ->
LspProtocol.sendResponse idNode (Some (JsonArray()))
let handleSignatureHelp (idNode: JsonNode) (paramsObj: JsonObject) =
match tryGetUriFromTextDocument paramsObj, tryGetPosition paramsObj with
| Some uri, Some (line, character) when documents.ContainsKey(uri) ->
let doc = documents[uri]
let tryResolveCallTargetFromInvocation () =
match getLineText doc.Text line with
| None -> None
| Some lineText ->
let pos = max 0 (min character lineText.Length)
let mutable idx = pos - 1
let mutable closeDepth = 0
let mutable openIdx = -1
while idx >= 0 && openIdx < 0 do
match lineText[idx] with
| ')' -> closeDepth <- closeDepth + 1
| '(' ->
if closeDepth = 0 then
openIdx <- idx
else
closeDepth <- closeDepth - 1
| _ -> ()
idx <- idx - 1
if openIdx <= 0 then None
else
let mutable finish = openIdx
while finish > 0 && Char.IsWhiteSpace(lineText[finish - 1]) do
finish <- finish - 1
let mutable start = finish - 1
while start >= 0 && isWordChar lineText[start] do
start <- start - 1
let tokenStart = start + 1
if tokenStart < finish then
Some (lineText.Substring(tokenStart, finish - tokenStart))
else
None
let computeActiveParameter () =
match getLineText doc.Text line with
| None -> 0
| Some lineText ->
let pos = max 0 (min character lineText.Length)
let mutable idx = pos - 1
let mutable closeDepth = 0
let mutable openIdx = -1
while idx >= 0 && openIdx < 0 do
match lineText[idx] with
| ')' -> closeDepth <- closeDepth + 1
| '(' ->
if closeDepth = 0 then
openIdx <- idx
else
closeDepth <- closeDepth - 1
| _ -> ()
idx <- idx - 1
if openIdx < 0 then 0
else