-
Notifications
You must be signed in to change notification settings - Fork 35
/
Server.fs
709 lines (553 loc) · 30.9 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
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 LanguageServerProtocol.Server
open LanguageServerProtocol
open LanguageServerProtocol.Types
open 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
type Options = {
SolutionPath: string option;
LogLevel: Types.MessageType;
}
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 ServerState = {
ClientCapabilities: ClientCapabilities option
Solution: Solution option
OpenDocVersions: Map<string, int>
DecompiledMetadataUris: Map<string, CSharpMetadataResponse>
DecompiledMetadataDocs: Map<string, Document>
}
let emptyServerState = { ClientCapabilities = None
Solution = None
OpenDocVersions = Map.empty
DecompiledMetadataUris = Map.empty
DecompiledMetadataDocs = Map.empty }
let getDocumentForUri state u =
let getPathUri path = Uri("file://" + path)
let uri = Uri u
match state.Solution with
| Some solution ->
let matchingDocuments = solution.Projects
|> Seq.collect (fun p -> p.Documents)
|> Seq.filter (fun d -> uri = getPathUri d.FilePath) |> List.ofSeq
match matchingDocuments with
| [d] -> //logMessage ("resolved to document " + d.FilePath + " while looking for " + uri.ToString())
Some d
| _ -> //logMessage (sprintf "getDocumentForUri: no document on solution matching uri %s" (uri |> string))
Map.tryFind u state.DecompiledMetadataDocs
| None -> None
let withDocumentOnUriOrNone state fn u = async {
match getDocumentForUri state u with
| Some doc ->
let! fnResult = fn doc
return fnResult
| None ->
return None
}
let getSymbolAtPosition state uri pos =
let resolveSymbolOrNull (doc: Document) = async {
let! sourceText = doc.GetTextAsync() |> Async.AwaitTask
let position = sourceText.Lines.GetPosition(LinePosition(pos.Line, pos.Character))
let! symbolRef = SymbolFinder.FindSymbolAtPositionAsync(doc, position) |> Async.AwaitTask
return if isNull symbolRef then None else Some (symbolRef, doc)
}
withDocumentOnUriOrNone state resolveSymbolOrNull uri
let isUriADecompiledDoc state u = Map.containsKey u state.DecompiledMetadataDocs
let withRegularDocumentOnUriOrUnit state fn u = async {
match isUriADecompiledDoc state u with
| true -> ()
| false ->
match getDocumentForUri state u with
| Some doc ->
let! fnResult = fn doc
return fnResult
| None ->
return ()
}
type CSharpLspServer(lspClient: CSharpLspClient, options: Options) =
inherit LspServer()
let mutable state: ServerState = emptyServerState
let logMessageWithLevel l message =
let messageParams = { Type = l ; Message = "csharp-ls: " + message }
do lspClient.WindowShowMessage messageParams |> ignore
let logMessage = logMessageWithLevel MessageType.Log
let infoMessage = logMessageWithLevel MessageType.Info
let warningMessage = logMessageWithLevel MessageType.Warning
let errorMessage = logMessageWithLevel MessageType.Error
let publishDiagnosticsOnDocument docUri (doc: Document) = async {
let! semanticModel = doc.GetSemanticModelAsync() |> Async.AwaitTask
let diagnostics = semanticModel.GetDiagnostics()
|> Seq.map RoslynHelpers.roslynToLspDiagnostic
|> Array.ofSeq
do! lspClient.TextDocumentPublishDiagnostics {
Uri = docUri
Diagnostics = diagnostics }
return ()
}
member _.State
with get() = state
and set(newState) = state <- newState
member __.LogMessage(s: string) = s |> logMessage
override __.Dispose(): unit = ()
override _.Initialize(p: InitializeParams) = async {
state <- { state with ClientCapabilities = p.Capabilities }
infoMessage (sprintf "initializing, csharp-ls version %s; options are: %s"
(typeof<CSharpLspServer>.Assembly.GetName().Version |> string)
(JsonConvert.SerializeObject(options, StringEnumConverter())))
infoMessage "csharp-ls is released under MIT license and is not affiliated with Microsoft Corp.; see https://github.com/razzmatazz/csharp-language-server"
match options.SolutionPath with
| Some solutionPath ->
infoMessage (sprintf "Initialize: loading specified solution file: %s.." solutionPath)
let! solutionLoaded = tryLoadSolutionOnPath logMessage solutionPath
state <- { state with Solution = solutionLoaded }
| None ->
let cwd = Directory.GetCurrentDirectory()
infoMessage (sprintf "attempting to find and load solution based on cwd: \"%s\".." cwd)
let! solutionLoaded = findAndLoadSolutionOnDir logMessage cwd
state <- { state with Solution = solutionLoaded }
infoMessage "ok, solution loaded -- initialization finished"
return
{ InitializeResult.Default with
Capabilities =
{ ServerCapabilities.Default with
HoverProvider = Some true
RenameProvider = Some true
DefinitionProvider = Some true
TypeDefinitionProvider = Some false
ImplementationProvider = Some true
ReferencesProvider = Some true
DocumentHighlightProvider = Some true
DocumentSymbolProvider = Some true
WorkspaceSymbolProvider = Some true
DocumentFormattingProvider = Some false
DocumentRangeFormattingProvider = Some false
SignatureHelpProvider = None
CompletionProvider =
Some { ResolveProvider = None
TriggerCharacters = Some ([| '.'; '''; |])
AllCommitCharacters = None
}
CodeLensProvider = None
CodeActionProvider =
Some { CodeActionKinds = None
ResolveProvider = Some true
}
TextDocumentSync =
Some { TextDocumentSyncOptions.Default with
OpenClose = Some false
Save = Some { IncludeText = Some true }
Change = Some TextDocumentSyncKind.Full
}
FoldingRangeProvider = Some false
SelectionRangeProvider = Some false
SemanticTokensProvider = None
}
}
|> success
}
override __.TextDocumentDidOpen(openParams: Types.DidOpenTextDocumentParams) =
state <- { state with OpenDocVersions = state.OpenDocVersions.Add(openParams.TextDocument.Uri, openParams.TextDocument.Version) }
withRegularDocumentOnUriOrUnit
state
(publishDiagnosticsOnDocument openParams.TextDocument.Uri)
openParams.TextDocument.Uri
override __.TextDocumentDidChange(changeParams: Types.DidChangeTextDocumentParams): Async<unit> =
let publishDiagnosticsOnUpdatedDocument (doc: Document) = async {
let fullText = SourceText.From(changeParams.ContentChanges.[0].Text)
let updatedDoc = doc.WithText(fullText)
let updatedSolution = updatedDoc.Project.Solution;
state <- { state with Solution = Some updatedSolution }
do! publishDiagnosticsOnDocument changeParams.TextDocument.Uri updatedDoc
return ()
}
state <- { state with OpenDocVersions = state.OpenDocVersions.Add(changeParams.TextDocument.Uri,
changeParams.TextDocument.Version |> Option.defaultValue 0) }
withRegularDocumentOnUriOrUnit
state
publishDiagnosticsOnUpdatedDocument
changeParams.TextDocument.Uri
override __.TextDocumentDidSave(saveParams: Types.DidSaveTextDocumentParams): Async<unit> = async {
// we need to add this file to solution if not already
match getDocumentForUri state saveParams.TextDocument.Uri with
| None ->
let solution = state.Solution.Value
let docFilePath = saveParams.TextDocument.Uri.Substring("file://".Length)
let docDir = Path.GetDirectoryName(docFilePath)
//logMessage (sprintf "TextDocumentDidSave: docFilename=%s docDir=%s" docFilename docDir)
let matchesPath (p: Project) =
let projectDir = Path.GetDirectoryName(p.FilePath)
(docDir |> string).StartsWith(projectDir |> string)
let projectOnPath = solution.Projects |> Seq.filter matchesPath |> Seq.tryHead
match projectOnPath with
| Some proj ->
let projectBaseDir = Path.GetDirectoryName(proj.FilePath)
let docName = docFilePath.Substring(projectBaseDir.Length+1)
logMessage (sprintf "Adding file %s (\"%s\") to project %s" docName docFilePath proj.FilePath)
let newDoc = proj.AddDocument(name=docName, text=SourceText.From(saveParams.Text.Value), folders=null, filePath=docFilePath)
//logMessage (sprintf "newDoc.FilePath=%s" (newDoc.FilePath |> string))
state <- { state with Solution = Some newDoc.Project.Solution }
do! publishDiagnosticsOnDocument saveParams.TextDocument.Uri newDoc
| None -> ()
| _ -> ()
return ()
}
override __.TextDocumentDidClose(closeParams: Types.DidCloseTextDocumentParams): Async<unit> = async {
state <- { state with OpenDocVersions = state.OpenDocVersions.Remove(closeParams.TextDocument.Uri) }
return ()
}
let handleTextDocumentCodeAction state logMessage (actionParams: Types.CodeActionParams): AsyncLspResult<Types.TextDocumentCodeActionResult option> = async {
match getDocumentForUri state actionParams.TextDocument.Uri with
| None ->
return None |> success
| Some doc ->
let! docText = doc.GetTextAsync() |> Async.AwaitTask
let textSpan = actionParams.Range |> roslynLinePositionSpanForLspRange
|> docText.Lines.GetTextSpan
let! roslynCodeActions = getRoslynCodeActions doc textSpan
let clientCapabilities = state.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 lspCa = roslynCodeActionToUnresolvedLspCodeAction ca
{ lspCa with Data = JsonConvert.SerializeObject(resolutionData) }
return roslynCodeActions |> Seq.map toUnresolvedLspCodeAction |> Array.ofSeq
}
| false -> async {
let results = List<CodeAction>()
for ca in roslynCodeActions do
let! maybeLspCa = roslynCodeActionToResolvedLspCodeAction state.Solution.Value
state.OpenDocVersions.TryFind
logMessage
ca
if maybeLspCa.IsSome then
results.Add(maybeLspCa.Value)
return results |> Array.ofSeq
}
return lspCodeActions
|> TextDocumentCodeActionResult.CodeActions
|> Some
|> success
}
let handleCodeActionResolve state logMessage (codeAction: CodeAction): AsyncLspResult<CodeAction option> = async {
let resolutionData = JsonConvert.DeserializeObject<CSharpCodeActionResolutionData>(codeAction.Data :?> string)
match getDocumentForUri state resolutionData.TextDocumentUri with
| None ->
return None |> success
| Some doc ->
let! docText = doc.GetTextAsync() |> Async.AwaitTask
let textSpan = resolutionData.Range |> roslynLinePositionSpanForLspRange
|> docText.Lines.GetTextSpan
let! roslynCodeActions = getRoslynCodeActions doc textSpan
let selectedCodeAction = roslynCodeActions |> Seq.tryFind (fun ca -> ca.Title = codeAction.Title)
let toResolvedLspCodeAction =
roslynCodeActionToResolvedLspCodeAction state.Solution.Value
state.OpenDocVersions.TryFind
logMessage
let! maybeLspCodeAction =
match selectedCodeAction with
| Some ca -> async { return! toResolvedLspCodeAction ca }
| None -> async { return None }
return maybeLspCodeAction |> success
}
let handleTextDocumentDefinitionOrImpl state logMessage (def: Types.TextDocumentPositionParams): Async<(LspResult<Types.GotoResult option> * ServerState)> = async {
let resolveDefinition (doc: Document) = task {
let! sourceText = doc.GetTextAsync()
let position = sourceText.Lines.GetPosition(LinePosition(def.Position.Line, def.Position.Character))
let! symbol = SymbolFinder.FindSymbolAtPositionAsync(doc, position)
let! compilation = doc.Project.GetCompilationAsync()
let! (locations, newState) = task {
match symbol with
| null -> //logMessage "no symbol at this point"
return ([], state)
| sym ->
//logMessage ("have symbol " + sym.ToString() + " at this point!")
// TODO:
// - handle symbols in metadata
let locationsInSource = sym.Locations |> Seq.filter (fun l -> l.IsInSource)
let locationsInMetadata = sym.Locations |> Seq.filter (fun l -> l.IsInMetadata)
let haveLocationsInMetadata = locationsInMetadata |> Seq.isEmpty |> not
if haveLocationsInMetadata then
let mdLocation = Seq.head locationsInMetadata
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 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 fullName = sym |> getContainingTypeOrThis |> getFullReflectionName
let fullTypeName = ICSharpCode.Decompiler.TypeSystem.FullTypeName(fullName)
let text = decompiler.DecompileTypeAsString(fullTypeName)
let uri = $"csharp:/metadata/projects/{doc.Project.Name}/assemblies/{mdLocation.MetadataModule.ContainingAssembly.Name}/symbols/{fullName}.cs"
let csharpMetadata = { ProjectName = doc.Project.Name;
AssemblyName = mdLocation.MetadataModule.ContainingAssembly.Name;
SymbolName = fullName;
Source = text }
let mdDocumentFilename = $"$metadata$/projects/{doc.Project.Name}/assemblies/{mdLocation.MetadataModule.ContainingAssembly.Name}/symbols/{fullName}.cs"
let mdProject = doc.Project
let mdDocumentEmpty = mdProject.AddDocument(mdDocumentFilename, String.Empty)
let mdDocument = SourceText.From(text) |> mdDocumentEmpty.WithText
let newState = { state with DecompiledMetadataUris = state.DecompiledMetadataUris |> Map.add uri csharpMetadata
DecompiledMetadataDocs = state.DecompiledMetadataDocs |> Map.add uri mdDocument }
// figure out location on the document (approx implementation)
let! syntaxTree = mdDocument.GetSyntaxTreeAsync()
let collector = DocumentSymbolCollectorForMatchingSymbolName(uri, sym.Name)
collector.Visit(syntaxTree.GetRoot())
let fallbackLocationInMetadata = {
Uri = uri
Range = { Start = { Line = 0; Character = 0 }; End = { Line = 0; Character = 1 } } }
let locationInMetadata =
(collector.GetLocations() @ [ fallbackLocationInMetadata ])
|> Seq.head
return ([locationInMetadata], newState)
else
let lspLocations = match List.ofSeq locationsInSource with
| [] -> []
| locations -> locations
|> Seq.map lspLocationForRoslynLocation
|> List.ofSeq
return (lspLocations, state)
}
return (locations, newState)
}
match getDocumentForUri state def.TextDocument.Uri with
| Some doc -> let! (locations, newState) = resolveDefinition doc |> Async.AwaitTask
let result = locations |> Array.ofSeq |> GotoResult.Multiple
return (Some result |> success, newState)
| None ->
logMessage (sprintf "getDocumentForUri: no document for uri %s" (def.TextDocument.Uri |> string))
return (None |> success, state)
}
let handleTextDocumentCompletion state _logMessage (posParams: Types.CompletionParams): AsyncLspResult<Types.CompletionList option> = async {
match getDocumentForUri state posParams.TextDocument.Uri with
| Some doc ->
let! docText = doc.GetTextAsync() |> 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
}
let handleTextDocumentDocumentHighlight state _logMessage (docParams: Types.TextDocumentPositionParams): AsyncLspResult<Types.DocumentHighlight [] option> = async {
let getSymbolLocations symbol doc solution = async {
let docSet = ImmutableHashSet<Document>.Empty.Add(doc)
let! refs = SymbolFinder.FindReferencesAsync(symbol, solution, docSet) |> Async.AwaitTask
let locationsFromRefs = refs |> Seq.collect (fun r -> r.Locations) |> Seq.map (fun rl -> rl.Location)
let! defRef = SymbolFinder.FindSourceDefinitionAsync(symbol, solution) |> Async.AwaitTask
let locationsFromDef = match Option.ofObj defRef with
// TODO: we might need to skip locations that are on a different document than this one
| Some sym -> sym.Locations |> List.ofSeq
| None -> []
return (Seq.append locationsFromRefs locationsFromDef)
|> Seq.map (fun l -> { Range = (lspLocationForRoslynLocation l).Range ;
Kind = Some DocumentHighlightKind.Read })
}
let shouldHighlight (symbol: ISymbol) =
match symbol with
| :? INamespaceSymbol -> false
| _ -> true
match state.Solution with
| Some solution ->
let! maybeSymbol = getSymbolAtPosition state docParams.TextDocument.Uri docParams.Position
match maybeSymbol with
| Some (symbol, doc) ->
if shouldHighlight symbol then
let! locations = getSymbolLocations symbol doc solution
return locations |> Array.ofSeq |> Some |> success
else
return None |> success
| None -> return None |> success
| None -> return None |> success
}
let handleTextDocumentDocumentSymbol state _logMessage (p: Types.DocumentSymbolParams): AsyncLspResult<Types.SymbolInformation [] option> = async {
match getDocumentForUri state p.TextDocument.Uri with
| Some doc ->
let collector = DocumentSymbolCollector(p.TextDocument.Uri)
let! syntaxTree = doc.GetSyntaxTreeAsync() |> Async.AwaitTask
collector.Visit(syntaxTree.GetRoot())
return collector.GetSymbols() |> Some |> success
| None ->
return None |> success
}
let handleTextDocumentHover state _logMessage (hoverPos: Types.TextDocumentPositionParams): AsyncLspResult<Types.Hover option> = async {
let! maybeSymbol = getSymbolAtPosition state hoverPos.TextDocument.Uri hoverPos.Position
let getSymbolDocumentation (sym: ISymbol) =
let csharpMarkdownDoc =
let containingAssemblyName =
sym.ContainingAssembly |> Option.ofObj |> Option.map (fun a -> a.Name) |> Option.defaultValue ""
Documentation.formatDocXmlWithTypeInfo
(sym.GetDocumentationCommentXml())
(sym.ToString())
containingAssemblyName
//logMessage (sprintf "debug: xml=%s; markdown=%s" (sym.GetDocumentationCommentXml()) csharpMarkdownDoc)
[MarkedString.WithLanguage { Language = "markdown"; Value = csharpMarkdownDoc }]
let suggestUnderlyingSymbolType (sym: ISymbol) =
match sym with
| :? ILocalSymbol as ps -> ps.Type :> ISymbol
| _ -> sym
let contents =
match maybeSymbol with
| Some (sym, _) -> sym |> suggestUnderlyingSymbolType |> getSymbolDocumentation
| _ -> []
return Some { Contents = contents |> Array.ofSeq |> MarkedStrings
Range = None } |> success
}
let handleTextDocumentReferences state _logMessage (refParams: Types.ReferenceParams): AsyncLspResult<Types.Location [] option> = async {
match state.Solution with
| Some solution ->
let! maybeSymbol = getSymbolAtPosition state refParams.TextDocument.Uri refParams.Position
match maybeSymbol with
| Some (symbol, _) ->
let! refs = SymbolFinder.FindReferencesAsync(symbol, solution) |> Async.AwaitTask
return refs |> Seq.collect (fun r -> r.Locations)
|> Seq.map (fun rl -> lspLocationForRoslynLocation rl.Location)
|> Array.ofSeq
|> Some
|> success
| None -> return None |> success
| None -> return None |> success
}
let handleTextDocumentRename state _logMessage (rename: Types.RenameParams): AsyncLspResult<Types.WorkspaceEdit option> = async {
let renameSymbolInDoc symbol (doc: Document) = async {
let originalSolution = doc.Project.Solution
let! updatedSolution =
Renamer.RenameSymbolAsync(doc.Project.Solution,
symbol,
rename.NewName,
doc.Project.Solution.Workspace.Options)
|> Async.AwaitTask
let! docTextEdit =
lspDocChangesFromSolutionDiff originalSolution
updatedSolution
state.OpenDocVersions.TryFind
return docTextEdit
}
let! maybeSymbol = getSymbolAtPosition state rename.TextDocument.Uri rename.Position
let! docChanges = match maybeSymbol with
| Some (symbol, doc) -> renameSymbolInDoc symbol doc
| None -> async { return [] }
return WorkspaceEdit.Create (docChanges |> Array.ofList, state.ClientCapabilities.Value) |> Some |> success
}
let handleWorkspaceSymbol state _logMessage (symbolParams: Types.WorkspaceSymbolParams): AsyncLspResult<Types.SymbolInformation [] option> = async {
let! symbols = findSymbols state.Solution.Value symbolParams.Query (Some 20)
return symbols |> Array.ofSeq |> Some |> success
}
let handleCSharpMetadata state _logMessage (metadataParams: CSharpMetadataParams): AsyncLspResult<CSharpMetadataResponse option> = async {
let uri = metadataParams.TextDocument.Uri
return state.DecompiledMetadataUris |> Map.tryFind uri |> success
}
let startCore options =
use input = Console.OpenStandardInput()
use output = Console.OpenStandardOutput()
let requestHandlingWithStateChange fn =
let wrappedHandler (s: CSharpLspServer) p = async {
let! (response, newState) = fn s.State s.LogMessage p
s.State <- newState
return response
}
requestHandling wrappedHandler
let requestHandlingWithState fn =
requestHandling (fun (s: CSharpLspServer) p -> fn s.State s.LogMessage p)
let requestHandlings =
defaultRequestHandlings<CSharpLspServer> ()
|> Map.add "textDocument/codeAction" (handleTextDocumentCodeAction |> requestHandlingWithState)
|> Map.add "codeAction/resolve" (handleCodeActionResolve |> requestHandlingWithState)
|> Map.add "textDocument/definition" (handleTextDocumentDefinitionOrImpl |> requestHandlingWithStateChange)
|> Map.add "textDocument/implementation" (handleTextDocumentDefinitionOrImpl |> requestHandlingWithStateChange)
|> Map.add "textDocument/completion" (handleTextDocumentCompletion |> requestHandlingWithState)
|> Map.add "textDocument/documentHighlight" (handleTextDocumentDocumentHighlight |> requestHandlingWithState)
|> Map.add "textDocument/documentSymbol" (handleTextDocumentDocumentSymbol |> requestHandlingWithState)
|> Map.add "textDocument/hover" (handleTextDocumentHover |> requestHandlingWithState)
|> Map.add "textDocument/references" (handleTextDocumentReferences |> requestHandlingWithState)
|> Map.add "textDocument/rename" (handleTextDocumentRename |> requestHandlingWithState)
|> Map.add "workspace/symbol" (handleWorkspaceSymbol |> requestHandlingWithState)
|> Map.add "csharp/metadata" (handleCSharpMetadata |> requestHandlingWithState)
LanguageServerProtocol.Server.start requestHandlings
input
output
CSharpLspClient
(fun lspClient -> new CSharpLspServer(lspClient, options))
let start options =
try
let result = startCore options
int result
with
| _ex ->
// logger.error (Log.setMessage "Start - LSP mode crashed" >> Log.addExn ex)
3