-
Notifications
You must be signed in to change notification settings - Fork 35
/
Server.fs
1338 lines (1072 loc) · 57.3 KB
/
Server.fs
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
module CSharpLanguageServer.Server
open System
open System.IO
open System.Collections.Generic
open System.Collections.Immutable
open Microsoft.CodeAnalysis
open Microsoft.CodeAnalysis.FindSymbols
open Microsoft.CodeAnalysis.Text
open Microsoft.CodeAnalysis.Completion
open Microsoft.CodeAnalysis.Rename
open Ionide.LanguageServerProtocol.Server
open Ionide.LanguageServerProtocol
open Ionide.LanguageServerProtocol.Types
open Ionide.LanguageServerProtocol.LspResult
open RoslynHelpers
open Microsoft.CodeAnalysis.CodeFixes
open ICSharpCode.Decompiler.CSharp
open ICSharpCode.Decompiler
open ICSharpCode.Decompiler.CSharp.Transforms
open Newtonsoft.Json
open Newtonsoft.Json.Converters
open Newtonsoft.Json.Linq
type Options = {
SolutionPath: string option;
LogLevel: Types.MessageType;
}
let emptyOptions = { SolutionPath = None; LogLevel = Types.MessageType.Log }
type CSharpLspClient(sendServerNotification: ClientNotificationSender, sendServerRequest: ClientRequestSender) =
inherit LspClient ()
override __.WindowShowMessage(p) =
sendServerNotification "window/showMessage" (box p) |> Async.Ignore
override __.WindowShowMessageRequest(p) =
sendServerRequest.Send "window/showMessageRequest" (box p)
override __.WindowLogMessage(p) =
sendServerNotification "window/logMessage" (box p) |> Async.Ignore
override __.TelemetryEvent(p) =
sendServerNotification "telemetry/event" (box p) |> Async.Ignore
override __.ClientRegisterCapability(p) =
sendServerRequest.Send "client/registerCapability" (box p)
override __.ClientUnregisterCapability(p) =
sendServerRequest.Send "client/unregisterCapability" (box p)
override __.WorkspaceWorkspaceFolders () =
sendServerRequest.Send "workspace/workspaceFolders" ()
override __.WorkspaceConfiguration (p) =
sendServerRequest.Send "workspace/configuration" (box p)
override __.WorkspaceApplyEdit (p) =
sendServerRequest.Send "workspace/applyEdit" (box p)
override __.WorkspaceSemanticTokensRefresh () =
sendServerNotification "workspace/semanticTokens/refresh" () |> Async.Ignore
override __.TextDocumentPublishDiagnostics(p) =
sendServerNotification "textDocument/publishDiagnostics" (box p) |> Async.Ignore
type CSharpMetadataParams = {
TextDocument: TextDocumentIdentifier
}
type CSharpMetadataResponse = {
ProjectName: string;
AssemblyName: string;
SymbolName: string;
Source: string;
}
type CSharpCodeActionResolutionData = {
TextDocumentUri: string
Range: Range
}
type DecompiledMetadataDocument = { Metadata: CSharpMetadataResponse; Document: Document }
type ServerDocumentType =
| UserDocument // user Document from solution, on disk
| DecompiledDocument // Document decompiled from metadata, readonly
| AnyDocument
type ServerState = {
ClientCapabilities: ClientCapabilities option
Solution: Solution option
OpenDocVersions: Map<string, int>
DecompiledMetadata: Map<string, DecompiledMetadataDocument>
Options: Options
RunningChangeRequest: AsyncReplyChannel<ServerState> option
ChangeRequestQueue: AsyncReplyChannel<ServerState> list
SolutionReloadPending: DateTime option
}
let emptyServerState = { ClientCapabilities = None
Solution = None
OpenDocVersions = Map.empty
DecompiledMetadata = Map.empty
Options = emptyOptions
RunningChangeRequest = None
ChangeRequestQueue = []
SolutionReloadPending = None }
let getDocumentOfTypeForUri state docType (u: string) =
let uri = Uri u
match state.Solution with
| Some solution ->
let matchingUserDocuments =
solution.Projects
|> Seq.collect (fun p -> p.Documents)
|> Seq.filter (fun d -> Uri("file://" + d.FilePath) = uri) |> List.ofSeq
let matchingUserDocumentMaybe =
match matchingUserDocuments with
| [d] -> Some (d, UserDocument)
| _ -> None
let matchingDecompiledDocumentMaybe =
Map.tryFind u state.DecompiledMetadata
|> Option.map (fun x -> (x.Document, DecompiledDocument))
match docType with
| UserDocument -> matchingUserDocumentMaybe
| DecompiledDocument -> matchingDecompiledDocumentMaybe
| AnyDocument -> matchingUserDocumentMaybe |> Option.orElse matchingDecompiledDocumentMaybe
| None -> None
type ServerStateEvent =
| ClientCapabilityChange of ClientCapabilities option
| SolutionChange of Solution
| DecompiledMetadataAdd of string * DecompiledMetadataDocument
| OpenDocVersionAdd of string * int
| OpenDocVersionRemove of string
| GetState of AsyncReplyChannel<ServerState>
| StartSolutionChange of AsyncReplyChannel<ServerState>
| FinishSolutionChange
| SolutionReloadRequest
| SolutionReload
| PeriodicTimerTick
let makeDocumentFromMetadata
(compilation: Microsoft.CodeAnalysis.Compilation)
(project: Microsoft.CodeAnalysis.Project)
(l: Microsoft.CodeAnalysis.Location)
(fullName: string) =
let mdLocation = l
let reference = compilation.GetMetadataReference(mdLocation.MetadataModule.ContainingAssembly)
let peReference = reference :?> PortableExecutableReference |> Option.ofObj
let assemblyLocation = peReference |> Option.map (fun r -> r.FilePath) |> Option.defaultValue "???"
let decompilerSettings = DecompilerSettings()
decompilerSettings.ThrowOnAssemblyResolveErrors <- false // this shouldn't be a showstopper for us
let decompiler = CSharpDecompiler(assemblyLocation, decompilerSettings)
// Escape invalid identifiers to prevent Roslyn from failing to parse the generated code.
// (This happens for example, when there is compiler-generated code that is not yet recognized/transformed by the decompiler.)
decompiler.AstTransforms.Add(EscapeInvalidIdentifiers())
let fullTypeName = ICSharpCode.Decompiler.TypeSystem.FullTypeName(fullName)
let text = decompiler.DecompileTypeAsString(fullTypeName)
let mdDocumentFilename = $"$metadata$/projects/{project.Name}/assemblies/{mdLocation.MetadataModule.ContainingAssembly.Name}/symbols/{fullName}.cs"
let mdDocumentEmpty = project.AddDocument(mdDocumentFilename, String.Empty)
let mdDocument = SourceText.From(text) |> mdDocumentEmpty.WithText
(mdDocument, text)
let resolveSymbolLocation
(state: ServerState)
(compilation: Microsoft.CodeAnalysis.Compilation)
(project: Microsoft.CodeAnalysis.Project)
sym
(l: Microsoft.CodeAnalysis.Location)
(logMessage: string -> unit)
= async {
let! ct = Async.CancellationToken
if l.IsInMetadata then
let fullName = sym |> getContainingTypeOrThis |> getFullReflectionName
let uri = $"csharp:/metadata/projects/{project.Name}/assemblies/{l.MetadataModule.ContainingAssembly.Name}/symbols/{fullName}.cs"
let mdDocument, stateChanges =
match Map.tryFind uri state.DecompiledMetadata with
| Some value ->
(value.Document, [])
| None ->
let (documentFromMd, text) = makeDocumentFromMetadata compilation project l fullName
let csharpMetadata = { ProjectName = project.Name
AssemblyName = l.MetadataModule.ContainingAssembly.Name
SymbolName = fullName
Source = text }
(documentFromMd, [
DecompiledMetadataAdd (uri, { Metadata = csharpMetadata; Document = documentFromMd })])
// figure out location on the document (approx implementation)
let! syntaxTree = mdDocument.GetSyntaxTreeAsync(ct) |> Async.AwaitTask
let collector = DocumentSymbolCollectorForMatchingSymbolName(uri, sym, logMessage)
collector.Visit(syntaxTree.GetRoot())
let fallbackLocationInMetadata = {
Uri = uri
Range = { Start = { Line = 0; Character = 0 }; End = { Line = 0; Character = 1 } } }
let resolved =
match collector.GetLocations() with
| [] -> [fallbackLocationInMetadata]
| ls -> ls
return resolved, stateChanges
else if l.IsInSource then
let resolved = [lspLocationForRoslynLocation l]
return resolved, []
else
return [], []
}
let resolveSymbolLocations
(state: ServerState)
(project: Microsoft.CodeAnalysis.Project)
(symbols: Microsoft.CodeAnalysis.ISymbol list)
(logMessage: string -> unit)
= async {
let! ct = Async.CancellationToken
let! compilation = project.GetCompilationAsync(ct) |> Async.AwaitTask
let mutable aggregatedLspLocations = []
let mutable aggregatedStateChanges = []
for sym in symbols do
for l in sym.Locations do
let! (symLspLocations, stateChanges) =
resolveSymbolLocation state compilation project sym l logMessage
aggregatedLspLocations <- aggregatedLspLocations @ symLspLocations
aggregatedStateChanges <- aggregatedStateChanges @ stateChanges
return (aggregatedLspLocations, aggregatedStateChanges)
}
type CodeLensData = { DocumentUri: string; Position: Position }
let emptyCodeLensData = { DocumentUri=""; Position={ Line=0; Character=0 } }
let rec processServerEvent logMessage state msg: Async<ServerState> = async {
let! ct = Async.CancellationToken
match msg with
| GetState replyChannel ->
replyChannel.Reply(state)
return state
| StartSolutionChange replyChannel ->
// only reply if we don't have another request that would change solution;
// otherwise enqueue the `replyChannel` to the ChangeRequestQueue
match state.RunningChangeRequest with
| Some _req ->
return { state with
ChangeRequestQueue = state.ChangeRequestQueue @ [replyChannel] }
| None ->
replyChannel.Reply(state)
return { state with
RunningChangeRequest = Some replyChannel }
| FinishSolutionChange ->
let newState = { state with RunningChangeRequest = None }
return match state.ChangeRequestQueue with
| [] -> newState
| nextPendingRequest :: queueRemainder ->
nextPendingRequest.Reply(newState)
{ newState with
ChangeRequestQueue = queueRemainder
RunningChangeRequest = Some nextPendingRequest }
| ClientCapabilityChange cc ->
return { state with ClientCapabilities = cc }
| SolutionChange s ->
return { state with Solution = Some s }
| DecompiledMetadataAdd (uri, md) ->
let newDecompiledMd = Map.add uri md state.DecompiledMetadata
return { state with DecompiledMetadata = newDecompiledMd }
| OpenDocVersionAdd (doc, ver) ->
let newOpenDocVersions = Map.add doc ver state.OpenDocVersions
return { state with OpenDocVersions = newOpenDocVersions }
| OpenDocVersionRemove uri ->
let newOpenDocVersions = state.OpenDocVersions |> Map.remove uri
return { state with OpenDocVersions = newOpenDocVersions }
| SolutionReloadRequest ->
// we need to wait a bit before starting this so we
// can buffer many incoming requests at once
return { state with SolutionReloadPending = DateTime.Now.AddSeconds(5) |> Some }
| SolutionReload ->
let! solution =
match state.Options.SolutionPath with
| Some solutionPath -> async {
logMessage (sprintf "loading specified solution file: %s.." solutionPath)
return! tryLoadSolutionOnPath logMessage solutionPath
}
| None -> async {
let cwd = Directory.GetCurrentDirectory()
logMessage (sprintf "attempting to find and load solution based on cwd: \"%s\".." cwd)
return! findAndLoadSolutionOnDir logMessage cwd
}
return { state with Solution = solution }
| PeriodicTimerTick ->
let solutionReloadTime = state.SolutionReloadPending
|> Option.defaultValue (DateTime.Now.AddDays(1))
match solutionReloadTime < DateTime.Now with
| true ->
let! newState = processServerEvent logMessage state SolutionReload
return { newState with SolutionReloadPending = None }
| false ->
return state
}
let serverEventLoop logMessage initialState (inbox: MailboxProcessor<ServerStateEvent>) =
let rec loop state = async {
let! msg = inbox.Receive()
let! newState = msg |> processServerEvent logMessage state
return! loop newState
}
loop initialState
type ServerRequestScope (state: ServerState, emitServerEvent, onDispose: unit -> unit) =
let mutable solutionMaybe = state.Solution
interface IDisposable with
member _.Dispose() = onDispose()
member _.State = state
member _.ClientCapabilities = state.ClientCapabilities
member _.Solution = solutionMaybe.Value
member _.OpenDocVersions = state.OpenDocVersions
member _.DecompiledMetadata = state.DecompiledMetadata
member this.GetDocumentForUriOfType docType (u: string) =
let uri = Uri u
match solutionMaybe with
| Some solution ->
let matchingUserDocuments =
solution.Projects
|> Seq.collect (fun p -> p.Documents)
|> Seq.filter (fun d -> Uri("file://" + d.FilePath) = uri) |> List.ofSeq
let matchingUserDocumentMaybe =
match matchingUserDocuments with
| [d] -> Some (d, UserDocument)
| _ -> None
let matchingDecompiledDocumentMaybe =
Map.tryFind u this.DecompiledMetadata
|> Option.map (fun x -> (x.Document, DecompiledDocument))
match docType with
| UserDocument -> matchingUserDocumentMaybe
| DecompiledDocument -> matchingDecompiledDocumentMaybe
| AnyDocument -> matchingUserDocumentMaybe |> Option.orElse matchingDecompiledDocumentMaybe
| None -> None
member x.GetUserDocumentForUri (u: string) = x.GetDocumentForUriOfType UserDocument u |> Option.map fst
member x.GetAnyDocumentForUri (u: string) = x.GetDocumentForUriOfType AnyDocument u |> Option.map fst
member x.GetSymbolAtPositionOfType docType uri pos = async {
match x.GetDocumentForUriOfType docType uri with
| Some (doc, _docType) ->
let! ct = Async.CancellationToken
let! sourceText = doc.GetTextAsync(ct) |> Async.AwaitTask
let position = sourceText.Lines.GetPosition(LinePosition(pos.Line, pos.Character))
let! symbolRef = SymbolFinder.FindSymbolAtPositionAsync(doc, position, ct) |> Async.AwaitTask
return if isNull symbolRef then None else Some (symbolRef, doc, position)
| None ->
return None
}
member x.GetSymbolAtPositionOnAnyDocument uri pos = x.GetSymbolAtPositionOfType AnyDocument uri pos
member x.GetSymbolAtPositionOnUserDocument uri pos = x.GetSymbolAtPositionOfType UserDocument uri pos
member x.Emit ev =
match ev with
| SolutionChange newSolution ->
solutionMaybe <- Some newSolution
| _ -> ()
emitServerEvent ev
member x.EmitMany es = for e in es do x.Emit e
type DiagnosticsEvent =
| DocumentOpenOrChange of string * DateTime
| DocumentClose of string
| ProcessPendingDiagnostics
| DocumentBacklogUpdate
| DocumentRemoval of string
type DiagnosticsState = {
DocumentBacklog: string list
DocumentChanges: Map<string, DateTime>
}
let emptyDiagnosticsState = { DocumentBacklog = []; DocumentChanges = Map.empty }
let processDiagnosticsEvent logMessage
(lspClient: CSharpLspClient)
(getDocumentForUri: string -> Async<(Document * ServerDocumentType) option>)
(state: DiagnosticsState)
event =
match event with
| DocumentRemoval uri -> async {
let updatedDocumentChanges = state.DocumentChanges |> Map.remove uri
let newState = { state with DocumentChanges = updatedDocumentChanges }
return newState, [ DocumentBacklogUpdate ]
}
| DocumentOpenOrChange (uri, timestamp) -> async {
let newDocChanges = state.DocumentChanges |> Map.add uri timestamp
let newState = { state with DocumentChanges = newDocChanges }
return newState, [ DocumentBacklogUpdate ]
}
| DocumentBacklogUpdate -> async {
let newBacklog =
state.DocumentChanges
|> Seq.sortByDescending (fun kv -> kv.Value)
|> Seq.map (fun kv -> kv.Key)
|> List.ofSeq
let newState = { state with DocumentBacklog = newBacklog }
return newState, []
}
| DocumentClose uri -> async {
let prunedBacklog = state.DocumentBacklog
|> Seq.filter (fun x -> x <> uri)
|> List.ofSeq
let prunedDocumentChanges = state.DocumentChanges |> Map.remove uri
let newState = { state with DocumentBacklog = prunedBacklog
DocumentChanges = prunedDocumentChanges }
return newState, []
}
| ProcessPendingDiagnostics -> async {
let docUriMaybe, newBacklog =
match state.DocumentBacklog with
| [] -> (None, [])
| uri :: remainder -> (Some uri, remainder)
match docUriMaybe with
| Some docUri ->
let! docAndTypeMaybe = getDocumentForUri docUri
match docAndTypeMaybe with
| Some (doc, _) ->
let! ct = Async.CancellationToken
let! semanticModelMaybe = doc.GetSemanticModelAsync(ct) |> Async.AwaitTask
match semanticModelMaybe |> Option.ofObj with
| Some semanticModel ->
let diagnostics =
semanticModel.GetDiagnostics()
|> Seq.map RoslynHelpers.roslynToLspDiagnostic
|> Array.ofSeq
do! lspClient.TextDocumentPublishDiagnostics { Uri = docUri; Diagnostics = diagnostics }
| None -> ()
| None -> ()
| None -> ()
let eventsToPost = match newBacklog with
| [] -> []
| _ -> [ ProcessPendingDiagnostics ]
return { state with DocumentBacklog = newBacklog }, eventsToPost
}
let setupServerHandlers options lspClient =
let mutable logMessageCurrent = Action<string>(fun _ -> ())
let logMessageInvoke m = logMessageCurrent.Invoke(m)
let stateActor = MailboxProcessor.Start(
serverEventLoop logMessageInvoke { emptyServerState with Options = options })
let getDocumentForUriFromCurrentState docType uri = async {
let! state = stateActor.PostAndAsyncReply(GetState)
return getDocumentOfTypeForUri state docType uri
}
let diagnostics = MailboxProcessor.Start(
fun inbox -> async {
let rec loop state = async {
try
let! msg = inbox.Receive()
let! (newState, eventsToPost) =
processDiagnosticsEvent logMessageInvoke
lspClient
(getDocumentForUriFromCurrentState AnyDocument)
state
msg
for ev in eventsToPost do inbox.Post(ev)
return! loop newState
with
| ex -> logMessageInvoke (sprintf "unhandled exception in `diagnostics`: %s" (ex|>string))
raise ex
}
return! loop emptyDiagnosticsState
})
let mutable timer: System.Threading.Timer option = None
let setupTimer () =
timer <- Some (new System.Threading.Timer(
System.Threading.TimerCallback(
fun _ -> do diagnostics.Post(ProcessPendingDiagnostics)
do stateActor.Post(PeriodicTimerTick)),
null, dueTime=1000, period=250))
let logMessageWithLevel l message =
let messageParams = { Type = l ; Message = "csharp-ls: " + message }
do lspClient.WindowShowMessage messageParams |> Async.StartAsTask |> ignore
let logMessage = logMessageWithLevel MessageType.Log
let infoMessage = logMessageWithLevel MessageType.Info
let warningMessage = logMessageWithLevel MessageType.Warning
let errorMessage = logMessageWithLevel MessageType.Error
let handleInitialize (scope: ServerRequestScope) (p: InitializeParams): AsyncLspResult<InitializeResult> =
async {
logMessageCurrent <- Action<string>(logMessage)
infoMessage (sprintf "initializing, csharp-ls version %s; options are: %s"
(typeof<CSharpLspClient>.Assembly.GetName().Version |> string)
(options |> serialize |> string))
infoMessage "csharp-ls is released under MIT license and is not affiliated with Microsoft Corp.; see https://github.com/razzmatazz/csharp-language-server"
scope.Emit(ClientCapabilityChange p.Capabilities)
// registering w/client for didChangeWatchedFiles notifications"
let fileChangeWatcher = { GlobPattern = "**/*.{cs,csproj,sln}"
Kind = None }
let didChangeWatchedFilesRegistration: Types.Registration =
{ Id = "id:workspace/didChangeWatchedFiles"
Method = "workspace/didChangeWatchedFiles"
RegisterOptions = { Watchers = [| fileChangeWatcher |] } |> serialize |> Some
}
let! regResult = lspClient.ClientRegisterCapability(
{ Registrations = [| didChangeWatchedFilesRegistration |] })
match regResult with
| Ok _ -> ()
| Error error -> infoMessage (sprintf " ...didChangeWatchedFiles registration has failed with %s" (error |> string))
// setup timer so actors get period ticks
setupTimer ()
// start solution loading (on stateActor)
scope.Emit(SolutionReload)
return success {
InitializeResult.Default with
Capabilities =
{ ServerCapabilities.Default with
HoverProvider = Some true
RenameProvider = Some true
DefinitionProvider = Some true
TypeDefinitionProvider = None
ImplementationProvider = Some true
ReferencesProvider = Some true
DocumentHighlightProvider = Some true
DocumentSymbolProvider = Some true
WorkspaceSymbolProvider = Some true
DocumentFormattingProvider = Some true
DocumentRangeFormattingProvider = Some true
DocumentOnTypeFormattingProvider =
Some
{ FirstTriggerCharacter = ';'
MoreTriggerCharacter = Some([| '}'; ')' |]) }
SignatureHelpProvider = None
CompletionProvider =
Some { ResolveProvider = None
TriggerCharacters = Some ([| '.'; '''; |])
AllCommitCharacters = None
}
CodeLensProvider =
Some { ResolveProvider = Some true }
CodeActionProvider =
Some { CodeActionKinds = None
ResolveProvider = Some true
}
TextDocumentSync =
Some { TextDocumentSyncOptions.Default with
OpenClose = None
Save = Some { IncludeText = Some true }
Change = Some TextDocumentSyncKind.Incremental
}
FoldingRangeProvider = None
SelectionRangeProvider = None
SemanticTokensProvider = None
}
}
}
let handleTextDocumentDidOpen (scope: ServerRequestScope) (openParams: Types.DidOpenTextDocumentParams): Async<unit> =
async {
match scope.GetDocumentForUriOfType AnyDocument openParams.TextDocument.Uri with
| Some (doc, docType) ->
match docType with
| UserDocument ->
// we want to load the document in case it has been changed since we have the solution loaded
// also, as a bonus we can recover from corrupted document view in case document in roslyn solution
// went out of sync with editor
let updatedDoc = SourceText.From(openParams.TextDocument.Text) |> doc.WithText
scope.Emit(OpenDocVersionAdd (openParams.TextDocument.Uri, openParams.TextDocument.Version))
scope.Emit(SolutionChange updatedDoc.Project.Solution)
diagnostics.Post(
DocumentOpenOrChange (openParams.TextDocument.Uri, DateTime.Now))
| _ -> ()
| None ->
match openParams.TextDocument.Uri.StartsWith("file://") with
| true ->
// ok, this document is not on solution, register a new one
let docFilePath = openParams.TextDocument.Uri.Substring("file://".Length)
let newDocMaybe = tryAddDocument logMessage
docFilePath
openParams.TextDocument.Text
scope.Solution
match newDocMaybe with
| Some newDoc ->
scope.Emit(SolutionChange newDoc.Project.Solution)
diagnostics.Post(
DocumentOpenOrChange (openParams.TextDocument.Uri, DateTime.Now))
| None -> ()
| false -> ()
}
let handleTextDocumentDidChange (scope: ServerRequestScope) (changeParams: Types.DidChangeTextDocumentParams): Async<unit> =
async {
let docMaybe = scope.GetUserDocumentForUri changeParams.TextDocument.Uri
match docMaybe with
| Some doc ->
let! ct = Async.CancellationToken
let! sourceText = doc.GetTextAsync(ct) |> Async.AwaitTask
//logMessage (sprintf "TextDocumentDidChange: changeParams: %s" (string changeParams))
//logMessage (sprintf "TextDocumentDidChange: sourceText: %s" (string sourceText))
let updatedSourceText = sourceText |> applyLspContentChangesOnRoslynSourceText changeParams.ContentChanges
let updatedDoc = doc.WithText(updatedSourceText)
//logMessage (sprintf "TextDocumentDidChange: newSourceText: %s" (string updatedSourceText))
let updatedSolution = updatedDoc.Project.Solution
scope.Emit(SolutionChange updatedSolution)
scope.Emit(OpenDocVersionAdd (changeParams.TextDocument.Uri, changeParams.TextDocument.Version |> Option.defaultValue 0))
diagnostics.Post(
DocumentOpenOrChange (changeParams.TextDocument.Uri, DateTime.Now))
| None -> ()
}
let handleTextDocumentDidSave (scope: ServerRequestScope) (saveParams: Types.DidSaveTextDocumentParams): Async<unit> =
async {
// we need to add this file to solution if not already
let doc = scope.GetAnyDocumentForUri saveParams.TextDocument.Uri
match doc with
| Some _ -> ()
| None ->
let docFilePath = saveParams.TextDocument.Uri.Substring("file://".Length)
let newDocMaybe = tryAddDocument logMessage
docFilePath
saveParams.Text.Value
scope.Solution
match newDocMaybe with
| Some newDoc ->
scope.Emit(SolutionChange newDoc.Project.Solution)
diagnostics.Post(
DocumentOpenOrChange (saveParams.TextDocument.Uri, DateTime.Now))
| None -> ()
}
let handleTextDocumentDidClose (scope: ServerRequestScope) (closeParams: Types.DidCloseTextDocumentParams): Async<unit> =
scope.Emit(OpenDocVersionRemove closeParams.TextDocument.Uri)
diagnostics.Post(DocumentClose closeParams.TextDocument.Uri)
async.Return ()
let handleTextDocumentCodeAction (scope: ServerRequestScope) (actionParams: Types.CodeActionParams): AsyncLspResult<Types.TextDocumentCodeActionResult option> = async {
let docMaybe = scope.GetUserDocumentForUri actionParams.TextDocument.Uri
match docMaybe with
| None ->
return None |> success
| Some doc ->
let! ct = Async.CancellationToken
let! docText = doc.GetTextAsync(ct) |> Async.AwaitTask
let textSpan = actionParams.Range
|> roslynLinePositionSpanForLspRange
|> docText.Lines.GetTextSpan
let! roslynCodeActions = getRoslynCodeActions doc textSpan
let clientCapabilities = scope.ClientCapabilities
let clientSupportsCodeActionEditResolveWithEditAndData =
clientCapabilities.IsSome
&& (clientCapabilities.Value.TextDocument.IsSome)
&& (clientCapabilities.Value.TextDocument.Value.CodeAction.IsSome)
&& (clientCapabilities.Value.TextDocument.Value.CodeAction.Value.DataSupport = Some true)
&& (clientCapabilities.Value.TextDocument.Value.CodeAction.Value.ResolveSupport.IsSome)
&& (clientCapabilities.Value.TextDocument.Value.CodeAction.Value.ResolveSupport.Value.Properties |> Array.contains "edit")
let! lspCodeActions =
match clientSupportsCodeActionEditResolveWithEditAndData with
| true -> async {
let toUnresolvedLspCodeAction (ca: Microsoft.CodeAnalysis.CodeActions.CodeAction) =
let resolutionData: CSharpCodeActionResolutionData =
{ TextDocumentUri = actionParams.TextDocument.Uri
Range = actionParams.Range }
let caData = JsonConvert.SerializeObject(resolutionData)
let lspCa = roslynCodeActionToUnresolvedLspCodeAction ca
{ lspCa with Data = Some (caData :> obj) }
return roslynCodeActions |> Seq.map toUnresolvedLspCodeAction |> Array.ofSeq
}
| false -> async {
let results = List<CodeAction>()
for ca in roslynCodeActions do
let! maybeLspCa =
roslynCodeActionToResolvedLspCodeAction
scope.Solution
scope.OpenDocVersions.TryFind
logMessage
doc
ca
if maybeLspCa.IsSome then
results.Add(maybeLspCa.Value)
return results |> Array.ofSeq
}
return
lspCodeActions
|> Seq.sortByDescending (fun ca -> ca.IsPreferred)
|> Array.ofSeq
|> TextDocumentCodeActionResult.CodeActions
|> Some
|> success
}
let handleCodeActionResolve (scope: ServerRequestScope) (codeAction: CodeAction): AsyncLspResult<CodeAction option> = async {
let resolutionData =
codeAction.Data
|> Option.map (fun x -> x :?> string)
|> Option.map JsonConvert.DeserializeObject<CSharpCodeActionResolutionData>
let docMaybe = scope.GetUserDocumentForUri resolutionData.Value.TextDocumentUri
match docMaybe with
| None ->
return None |> success
| Some doc ->
let! ct = Async.CancellationToken
let! docText = doc.GetTextAsync(ct) |> Async.AwaitTask
let textSpan =
resolutionData.Value.Range
|> roslynLinePositionSpanForLspRange
|> docText.Lines.GetTextSpan
let! roslynCodeActions = getRoslynCodeActions doc textSpan
let selectedCodeAction = roslynCodeActions |> Seq.tryFind (fun ca -> ca.Title = codeAction.Title)
let toResolvedLspCodeAction =
roslynCodeActionToResolvedLspCodeAction
scope.Solution
scope.OpenDocVersions.TryFind
logMessage
doc
let! maybeLspCodeAction =
match selectedCodeAction with
| Some ca -> async { return! toResolvedLspCodeAction ca }
| None -> async { return None }
return maybeLspCodeAction |> success
}
let handleTextDocumentCodeLens (scope: ServerRequestScope) (lensParams: CodeLensParams): AsyncLspResult<CodeLens[] option> = async {
let docMaybe = scope.GetAnyDocumentForUri lensParams.TextDocument.Uri
match docMaybe with
| Some doc ->
let! ct = Async.CancellationToken
let! semanticModel = doc.GetSemanticModelAsync(ct) |> Async.AwaitTask
let! syntaxTree = doc.GetSyntaxTreeAsync(ct) |> Async.AwaitTask
let collector = DocumentSymbolCollectorForCodeLens(semanticModel)
collector.Visit(syntaxTree.GetRoot())
let makeCodeLens (_symbol: ISymbol, location: Microsoft.CodeAnalysis.Location): CodeLens =
let start = location.GetLineSpan().Span.Start
let lensData: CodeLensData = {
DocumentUri = lensParams.TextDocument.Uri
Position = start |> lspPositionForRoslynLinePosition
}
{ Range = (location.GetLineSpan().Span) |> lspRangeForRoslynLinePosSpan
Command = None
Data = lensData |> JToken.FromObject |> Some
}
let codeLens = collector.GetSymbols() |> Seq.map makeCodeLens
return codeLens |> Array.ofSeq |> Some |> success
| None ->
return None |> success
}
let handleCodeLensResolve (scope: ServerRequestScope) (codeLens: CodeLens) : AsyncLspResult<CodeLens> = async {
let lensData =
codeLens.Data
|> Option.map (fun t -> t.ToObject<CodeLensData>())
|> Option.defaultValue emptyCodeLensData
let docMaybe = scope.GetAnyDocumentForUri lensData.DocumentUri
let doc = docMaybe.Value
let! ct = Async.CancellationToken
let! sourceText = doc.GetTextAsync(ct) |> Async.AwaitTask
let position =
LinePosition(lensData.Position.Line, lensData.Position.Character)
|> sourceText.Lines.GetPosition
let! symbol = SymbolFinder.FindSymbolAtPositionAsync(doc, position, ct) |> Async.AwaitTask
let! refs = SymbolFinder.FindReferencesAsync(symbol, doc.Project.Solution, ct) |> Async.AwaitTask
let locations = refs |> Seq.collect (fun r -> r.Locations)
let formattedRefCount =
locations |> Seq.length |> sprintf "%d Reference(s)"
let command =
{ Title = formattedRefCount
Command = "csharp.showReferences"
Arguments = None // TODO: we really want to pass some more info to the client
}
return { codeLens with Command=Some command } |> success
}
let handleTextDocumentDefinition (scope: ServerRequestScope) (def: Types.TextDocumentPositionParams) : AsyncLspResult<Types.GotoResult option> = async {
let docMaybe = scope.GetAnyDocumentForUri def.TextDocument.Uri
return!
match docMaybe with
| Some doc -> async {
let! ct = Async.CancellationToken
let! sourceText = doc.GetTextAsync(ct) |> Async.AwaitTask
let position = sourceText.Lines.GetPosition(LinePosition(def.Position.Line, def.Position.Character))
let! symbolMaybe = SymbolFinder.FindSymbolAtPositionAsync(doc, position, ct) |> Async.AwaitTask
let symbols =
match Option.ofObj symbolMaybe with
| Some sym -> [sym]
| None -> []
let! (locations, stateChanges) =
resolveSymbolLocations scope.State doc.Project symbols logMessage
do scope.EmitMany stateChanges
return locations |> Array.ofSeq |> GotoResult.Multiple |> Some |> success
}
| None ->
None |> success |> async.Return
}
let handleTextDocumentImplementation (scope: ServerRequestScope) (def: Types.TextDocumentPositionParams): AsyncLspResult<Types.GotoResult option> = async {
let docMaybe = scope.GetAnyDocumentForUri def.TextDocument.Uri
return!
match docMaybe with
| Some doc -> async {
let! ct = Async.CancellationToken
let! sourceText = doc.GetTextAsync(ct) |> Async.AwaitTask
let position = sourceText.Lines.GetPosition(LinePosition(def.Position.Line, def.Position.Character))
let! symbolMaybe = SymbolFinder.FindSymbolAtPositionAsync(doc, position, ct) |> Async.AwaitTask
let! symbols = async {
match Option.ofObj symbolMaybe with
| Some sym ->
let! implSymbols =
SymbolFinder.FindImplementationsAsync(sym, scope.Solution)
|> Async.AwaitTask
return implSymbols |> List.ofSeq
| None -> return []
}
let! (locations, stateChanges) =
resolveSymbolLocations scope.State doc.Project symbols logMessage
do scope.EmitMany stateChanges
return locations |> Array.ofSeq |> GotoResult.Multiple |> Some |> success
}
| None -> async {
return None |> success
}
}
let handleTextDocumentCompletion (scope: ServerRequestScope) (posParams: Types.CompletionParams): AsyncLspResult<Types.CompletionList option> = async {
let docMaybe = scope.GetUserDocumentForUri posParams.TextDocument.Uri
match docMaybe with
| Some doc ->
let! ct = Async.CancellationToken
let! docText = doc.GetTextAsync(ct) |> Async.AwaitTask
let posInText = docText.Lines.GetPosition(LinePosition(posParams.Position.Line, posParams.Position.Character))
let completionService = CompletionService.GetService(doc)
if isNull completionService then
return ()
let! maybeCompletionResults = completionService.GetCompletionsAsync(doc, posInText)
|> Async.AwaitTask
match Option.ofObj maybeCompletionResults with
| Some completionResults ->
let makeLspCompletionItem (item: Microsoft.CodeAnalysis.Completion.CompletionItem) =
{ CompletionItem.Create(item.DisplayText) with
Kind = item.Tags |> Seq.head |> roslynTagToLspCompletion |> Some ;
InsertTextFormat = Some Types.InsertTextFormat.PlainText }
let completionList = {
IsIncomplete = false ;
Items = completionResults.Items
|> Seq.map makeLspCompletionItem
|> Array.ofSeq }
return success (Some completionList)
| None -> return success None
| None -> return success None
}