-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathAdaptiveServerState.fs
2226 lines (1758 loc) · 80.3 KB
/
AdaptiveServerState.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
namespace FsAutoComplete.Lsp
open System
open System.IO
open System.Threading
open FsAutoComplete
open FsAutoComplete.CodeFix
open FsAutoComplete.Logging
open Ionide.LanguageServerProtocol
open Ionide.LanguageServerProtocol.Types
open Ionide.ProjInfo.ProjectSystem
open System.Reactive
open FsAutoComplete.Adaptive
open FsAutoComplete.LspHelpers
open FSharp.Control.Reactive
open FsToolkit.ErrorHandling
open FsAutoComplete.Telemetry
open FsAutoComplete.Utils.Tracing
open FSharp.UMX
open FSharp.Compiler.Text
open CliWrap
open FSharp.Compiler.EditorServices
open FSharp.Data.Adaptive
open Ionide.ProjInfo
open FSharp.Compiler.CodeAnalysis
open FsAutoComplete.UnionPatternMatchCaseGenerator
open System.Collections.Concurrent
open System.Text.RegularExpressions
open IcedTasks
open System.Threading.Tasks
open FsAutoComplete.FCSPatches
open FsAutoComplete.Lsp
open FsAutoComplete.Lsp.Helpers
[<RequireQualifiedAccess>]
type WorkspaceChosen =
| Projs of HashSet<string<LocalPath>>
| NotChosen
[<RequireQualifiedAccess>]
type AdaptiveWorkspaceChosen =
| Projs of amap<string<LocalPath>, DateTime>
| NotChosen
[<CustomEquality; NoComparison>]
type LoadedProject =
{ FSharpProjectOptions: FSharpProjectOptions
LanguageVersion: LanguageVersionShim }
interface IEquatable<LoadedProject> with
member x.Equals(other) = x.FSharpProjectOptions = other.FSharpProjectOptions
override x.GetHashCode() = x.FSharpProjectOptions.GetHashCode()
override x.Equals(other: obj) =
match other with
| :? LoadedProject as other -> (x :> IEquatable<_>).Equals other
| _ -> false
member x.SourceFiles = x.FSharpProjectOptions.SourceFiles
member x.ProjectFileName = x.FSharpProjectOptions.ProjectFileName
static member op_Implicit(x: LoadedProject) = x.FSharpProjectOptions
/// The reality is a file can be in multiple projects
/// This is extracted to make it easier to do some type of customized select in the future
type IFindProject =
abstract member FindProject:
sourceFile: string<LocalPath> * projects: LoadedProject seq -> Result<LoadedProject, string>
type FindFirstProject() =
interface IFindProject with
member x.FindProject(sourceFile, projects) =
projects
|> Seq.sortBy (fun p -> p.ProjectFileName)
|> Seq.tryFind (fun p -> p.SourceFiles |> Array.exists (fun f -> f = UMX.untag sourceFile))
|> Result.ofOption (fun () ->
$"Couldn't find a corresponding project for {sourceFile}. Have the projects loaded yet or have you tried restoring your project/solution?")
type AdaptiveState(lspClient: FSharpLspClient, sourceTextFactory: ISourceTextFactory, workspaceLoader: IWorkspaceLoader)
=
let logger = LogProvider.getLoggerFor<AdaptiveState> ()
let thisType = typeof<AdaptiveState>
let disposables = new Disposables.CompositeDisposable()
let projectSelector = cval<IFindProject> (FindFirstProject())
let rootPath = cval<string option> None
let config = cval<FSharpConfig> FSharpConfig.Default
let checker =
config
|> AVal.map (fun c -> c.EnableAnalyzers, c.Fsac.CachedTypeCheckCount, c.Fsac.ParallelReferenceResolution)
|> AVal.map (FSharpCompilerServiceChecker)
let configChanges =
aval {
let! config = config
and! checker = checker
and! rootPath = rootPath
return config, checker, rootPath
}
let mutable traceNotifications: ProgressListener option = None
/// <summary>Toggles trace notifications on or off.</summary>
/// <param name="shouldTrace">Determines if tracing should occur</param>
/// <param name="traceNamespaces">The namespaces to start tracing</param>
/// <returns></returns>
let toggleTraceNotification shouldTrace traceNamespaces =
traceNotifications |> Option.iter dispose
if shouldTrace then
traceNotifications <- Some(new ProgressListener(lspClient, traceNamespaces))
else
traceNotifications <- None
/// <summary>Sets tje FSI arguments on the FSharpCompilerServiceChecker</summary>
/// <param name="checker"></param>
/// <param name="fsiCompilerToolLocations">Compiler tool locations</param>
/// <param name="fsiExtraParameters">Any extra parameters to pass to FSI</param>
let setFSIArgs
(checker: FSharpCompilerServiceChecker)
(fsiCompilerToolLocations: string array)
(fsiExtraParameters: seq<string>)
=
let toCompilerToolArgument (path: string) = sprintf "--compilertool:%s" path
checker.SetFSIAdditionalArguments
[| yield! fsiCompilerToolLocations |> Array.map toCompilerToolArgument
yield! fsiExtraParameters |]
let analyzersClient =
FSharp.Analyzers.SDK.Client<FSharp.Analyzers.SDK.EditorAnalyzerAttribute, FSharp.Analyzers.SDK.EditorContext>(
Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance
)
/// <summary>Loads F# Analyzers from the configured directories</summary>
/// <param name="config">The FSharpConfig</param>
/// <param name="rootPath">The RootPath</param>
/// <returns></returns>
let loadAnalyzers (config: FSharpConfig) (rootPath: string option) =
if config.EnableAnalyzers then
Loggers.analyzers.info (Log.setMessageI $"Using analyzer roots of {config.AnalyzersPath:roots}")
let excludeInclude =
match config.ExcludeAnalyzers, config.IncludeAnalyzers with
| e, [||] -> FSharp.Analyzers.SDK.ExcludeInclude.ExcludeFilter(fun (s: string) -> Array.contains s e)
| [||], i -> FSharp.Analyzers.SDK.ExcludeInclude.IncludeFilter(fun (s: string) -> Array.contains s i)
| _e, i ->
Loggers.analyzers.warn (
Log.setMessage
"--exclude-analyzers and --include-analyzers are mutually exclusive, ignoring --exclude-analyzers"
)
FSharp.Analyzers.SDK.ExcludeInclude.IncludeFilter(fun (s: string) -> Array.contains s i)
config.AnalyzersPath
|> Array.iter (fun analyzerPath ->
match rootPath with
| None -> ()
| Some workspacePath ->
let dir =
if
System.IO.Path.IsPathRooted analyzerPath
// if analyzer is using absolute path, use it as is
then
analyzerPath
// otherwise, it is a relative path and should be combined with the workspace path
else
System.IO.Path.Combine(workspacePath, analyzerPath)
Loggers.analyzers.info (Log.setMessageI $"Loading analyzers from {dir:dir}")
let assemblyLoadStats = analyzersClient.LoadAnalyzers(dir, excludeInclude)
Loggers.analyzers.info (
Log.setMessageI
$"From {analyzerPath:name}: {assemblyLoadStats.AnalyzerAssemblies:dllNo} dlls including {assemblyLoadStats.Analyzers:analyzersNo} analyzers"
))
else
Loggers.analyzers.info (Log.setMessage "Analyzers disabled")
/// <summary></summary>
/// <param name="checker">the FSharpCompilerServiceChecker</param>
/// <param name="dotnetRoot">The path to dotnet</param>
/// <param name="rootPath">The root path</param>
/// <returns></returns>
let setDotnetRoot (checker: FSharpCompilerServiceChecker) (dotnetRoot: string) (rootPath: string option) =
let di = DirectoryInfo dotnetRoot
if di.Exists then
let dotnetBinary =
if
System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(Runtime.InteropServices.OSPlatform.Windows)
then
FileInfo(Path.Combine(di.FullName, "dotnet.exe"))
else
FileInfo(Path.Combine(di.FullName, "dotnet"))
if dotnetBinary.Exists then
checker.SetDotnetRoot(dotnetBinary, defaultArg rootPath System.Environment.CurrentDirectory |> DirectoryInfo)
else
// if we were mistakenly given the path to a dotnet binary
// then use the parent directory as the dotnet root instead
let fi = FileInfo(di.FullName)
if fi.Exists && (fi.Name = "dotnet" || fi.Name = "dotnet.exe") then
checker.SetDotnetRoot(fi, defaultArg rootPath System.Environment.CurrentDirectory |> DirectoryInfo)
// Syncs config changes to the mutable world
do
AVal.Observable.onValueChangedWeak configChanges
|> Observable.subscribe (fun (config, checker, rootPath) ->
toggleTraceNotification config.Notifications.Trace config.Notifications.TraceNamespaces
setFSIArgs checker config.FSICompilerToolLocations config.FSIExtraParameters
loadAnalyzers config rootPath
setDotnetRoot checker config.DotNetRoot rootPath)
|> disposables.Add
let tfmConfig =
config
|> AVal.map (fun c ->
if c.UseSdkScripts then
FSIRefs.TFM.NetCore
else
FSIRefs.TFM.NetFx)
let sendDiagnostics (uri: DocumentUri) (diags: Diagnostic[]) =
logger.info (Log.setMessageI $"SendDiag for {uri:file}: {diags.Length:diags} entries")
// TODO: providing version would be very useful
{ Uri = uri
Diagnostics = diags
Version = None }
|> lspClient.TextDocumentPublishDiagnostics
let diagnosticCollections = new DiagnosticCollection(sendDiagnostics)
let notifications = Event<NotificationEvent * CancellationToken>()
let scriptFileProjectOptions = Event<FSharpProjectOptions>()
let fileParsed =
Event<FSharpParseFileResults * FSharpProjectOptions * CancellationToken>()
let fileChecked = Event<ParseAndCheckResults * VolatileFile * CancellationToken>()
let detectTests (parseResults: FSharpParseFileResults) (proj: FSharpProjectOptions) ct =
try
logger.info (Log.setMessageI $"Test Detection of {parseResults.FileName:file} started")
let fn = UMX.tag parseResults.FileName
let res =
if proj.OtherOptions |> Seq.exists (fun o -> o.Contains "Expecto.dll") then
TestAdapter.getExpectoTests parseResults.ParseTree
elif proj.OtherOptions |> Seq.exists (fun o -> o.Contains "nunit.framework.dll") then
TestAdapter.getNUnitTest parseResults.ParseTree
elif proj.OtherOptions |> Seq.exists (fun o -> o.Contains "xunit.assert.dll") then
TestAdapter.getXUnitTest parseResults.ParseTree
else
[]
logger.info (Log.setMessageI $"Test Detection of {parseResults.FileName:file} - {res:res}")
notifications.Trigger(NotificationEvent.TestDetected(fn, res |> List.toArray), ct)
with e ->
logger.info (
Log.setMessageI $"Test Detection of {parseResults.FileName:file} failed"
>> Log.addExn e
)
do
disposables.Add
<| fileParsed.Publish.Subscribe(fun (parseResults, proj, ct) -> detectTests parseResults proj ct)
let builtInCompilerAnalyzers config (file: VolatileFile) (tyRes: ParseAndCheckResults) =
let filePath = file.FileName
let filePathUntag = UMX.untag filePath
let source = file.Source
let version = file.Version
let fileName = Path.GetFileName filePathUntag
let inline getSourceLine lineNo = (source: ISourceText).GetLineString(lineNo - 1)
let checkUnusedOpens =
async {
try
use progress = new ServerProgressReport(lspClient)
do! progress.Begin($"Checking unused opens {fileName}...", message = filePathUntag)
let! unused = UnusedOpens.getUnusedOpens (tyRes.GetCheckResults, getSourceLine)
let! ct = Async.CancellationToken
notifications.Trigger(NotificationEvent.UnusedOpens(filePath, (unused |> List.toArray), file.Version), ct)
with e ->
logger.error (Log.setMessage "checkUnusedOpens failed" >> Log.addExn e)
}
let checkUnusedDeclarations =
async {
try
use progress = new ServerProgressReport(lspClient)
do! progress.Begin($"Checking unused declarations {fileName}...", message = filePathUntag)
let isScript = Utils.isAScript (filePathUntag)
let! unused = UnusedDeclarations.getUnusedDeclarations (tyRes.GetCheckResults, isScript)
let unused = unused |> Seq.toArray
let! ct = Async.CancellationToken
notifications.Trigger(NotificationEvent.UnusedDeclarations(filePath, unused, file.Version), ct)
with e ->
logger.error (Log.setMessage "checkUnusedDeclarations failed" >> Log.addExn e)
}
let checkSimplifiedNames =
async {
try
use progress = new ServerProgressReport(lspClient)
do! progress.Begin($"Checking simplifying of names {fileName}...", message = filePathUntag)
let! simplified = SimplifyNames.getSimplifiableNames (tyRes.GetCheckResults, getSourceLine)
let simplified = Array.ofSeq simplified
let! ct = Async.CancellationToken
notifications.Trigger(NotificationEvent.SimplifyNames(filePath, simplified, file.Version), ct)
with e ->
logger.error (Log.setMessage "checkSimplifiedNames failed" >> Log.addExn e)
}
let checkUnnecessaryParentheses =
async {
try
use progress = new ServerProgressReport(lspClient)
do! progress.Begin($"Checking for unnecessary parentheses {fileName}...", message = filePathUntag)
let! unnecessaryParentheses = UnnecessaryParentheses.getUnnecessaryParentheses getSourceLine tyRes.GetAST
let! ct = Async.CancellationToken
notifications.Trigger(
NotificationEvent.UnnecessaryParentheses(filePath, Array.ofSeq unnecessaryParentheses, file.Version),
ct
)
with e ->
logger.error (Log.setMessage "checkUnnecessaryParentheses failed" >> Log.addExn e)
}
let inline isNotExcluded (exclusions: Regex array) =
exclusions |> Array.exists (fun r -> r.IsMatch filePathUntag) |> not
let analyzers =
[
// if config.Linter then
// commands.Lint filePath |> Async .Ignore
if config.UnusedOpensAnalyzer && isNotExcluded config.UnusedOpensAnalyzerExclusions then
checkUnusedOpens
if
config.UnusedDeclarationsAnalyzer
&& isNotExcluded config.UnusedDeclarationsAnalyzerExclusions
then
checkUnusedDeclarations
if
config.SimplifyNameAnalyzer
&& isNotExcluded config.SimplifyNameAnalyzerExclusions
then
checkSimplifiedNames
if config.UnnecessaryParenthesesAnalyzer then
checkUnnecessaryParentheses ]
async {
do! analyzers |> Async.parallel75 |> Async.Ignore<unit[]>
do!
lspClient.NotifyDocumentAnalyzed
{ TextDocument =
{ Uri = filePath |> Path.LocalPathToUri
Version = version } }
}
let runAnalyzers (config: FSharpConfig) (parseAndCheck: ParseAndCheckResults) (volatileFile: VolatileFile) =
async {
if config.EnableAnalyzers then
let file = volatileFile.FileName
try
use progress = new ServerProgressReport(lspClient)
do! progress.Begin("Running analyzers...", message = UMX.untag file)
Loggers.analyzers.info (
Log.setMessage "begin analysis of {file}"
>> Log.addContextDestructured "file" file
)
match parseAndCheck.GetCheckResults.ImplementationFile with
| Some tast ->
// Since analyzers are not async, we need to switch to a new thread to not block threadpool
do! Async.SwitchToNewThread()
let! res =
Commands.analyzerHandler (
analyzersClient,
file,
volatileFile.Source,
parseAndCheck.GetParseResults,
tast,
parseAndCheck.GetCheckResults
)
let! ct = Async.CancellationToken
notifications.Trigger(NotificationEvent.AnalyzerMessage(res, file, volatileFile.Version), ct)
Loggers.analyzers.info (Log.setMessageI $"end analysis of {file:file}")
| _ ->
Loggers.analyzers.info (Log.setMessageI $"missing components of {file:file} to run analyzers, skipped them")
()
with ex ->
Loggers.analyzers.error (Log.setMessageI $"Run failed for {file:file}" >> Log.addExn ex)
}
do
disposables.Add
<| fileChecked.Publish.Subscribe(fun (parseAndCheck, volatileFile, ct) ->
if volatileFile.Source.Length = 0 then
() // Don't analyze and error on an empty file
else
async {
let config = config |> AVal.force
do! builtInCompilerAnalyzers config volatileFile parseAndCheck
do! runAnalyzers config parseAndCheck volatileFile
}
|> Async.StartWithCT ct)
let handleCommandEvents (n: NotificationEvent, ct: CancellationToken) =
try
async {
try
match n with
| NotificationEvent.FileParsed fn ->
let uri = Path.LocalPathToUri fn
do! ({ Content = UMX.untag uri }: PlainNotification) |> lspClient.NotifyFileParsed
| NotificationEvent.Workspace ws ->
let ws =
match ws with
| ProjectResponse.Project(x, _) -> CommandResponse.project JsonSerializer.writeJson x
| ProjectResponse.ProjectError(_, errorDetails) ->
CommandResponse.projectError JsonSerializer.writeJson errorDetails
| ProjectResponse.ProjectLoading(projectFileName) ->
CommandResponse.projectLoading JsonSerializer.writeJson projectFileName
| ProjectResponse.WorkspaceLoad(finished) ->
CommandResponse.workspaceLoad JsonSerializer.writeJson finished
| ProjectResponse.ProjectChanged(_projectFileName) -> failwith "Not Implemented"
logger.info (Log.setMessage "Workspace Notify {ws}" >> Log.addContextDestructured "ws" ws)
do! ({ Content = ws }: PlainNotification) |> lspClient.NotifyWorkspace
| NotificationEvent.ParseError(errors, file, version) ->
let uri = Path.LocalPathToUri file
let diags = errors |> Array.map fcsErrorToDiagnostic
diagnosticCollections.SetFor(uri, "F# Compiler", version, diags)
| NotificationEvent.UnusedOpens(file, opens, version) ->
let uri = Path.LocalPathToUri file
let diags =
opens
|> Array.map (fun n ->
{ Range = fcsRangeToLsp n
Code = Some "FSAC0001"
Severity = Some DiagnosticSeverity.Hint
Source = Some "FSAC"
Message = "Unused open statement"
RelatedInformation = None
Tags = Some [| DiagnosticTag.Unnecessary |]
Data = None
CodeDescription = None })
diagnosticCollections.SetFor(uri, "F# Unused opens", version, diags)
| NotificationEvent.UnusedDeclarations(file, decls, version) ->
let uri = Path.LocalPathToUri file
let diags =
decls
|> Array.map (fun n ->
{ Range = fcsRangeToLsp n
Code = Some "FSAC0003"
Severity = Some DiagnosticSeverity.Hint
Source = Some "FSAC"
Message = "This value is unused"
RelatedInformation = Some [||]
Tags = Some [| DiagnosticTag.Unnecessary |]
Data = None
CodeDescription = None })
diagnosticCollections.SetFor(uri, "F# Unused declarations", version, diags)
| NotificationEvent.SimplifyNames(file, decls, version) ->
let uri = Path.LocalPathToUri file
let diags =
decls
|> Array.map
(fun
({ Range = range
RelativeName = _relName }) ->
{ Diagnostic.Range = fcsRangeToLsp range
Code = Some "FSAC0002"
Severity = Some DiagnosticSeverity.Hint
Source = Some "FSAC"
Message = "This qualifier is redundant"
RelatedInformation = Some [||]
Tags = Some [| DiagnosticTag.Unnecessary |]
Data = None
CodeDescription = None })
diagnosticCollections.SetFor(uri, "F# simplify names", version, diags)
| NotificationEvent.UnnecessaryParentheses(file, ranges, version) ->
let uri = Path.LocalPathToUri file
let diags =
ranges
|> Array.map (fun range ->
{ Diagnostic.Range = fcsRangeToLsp range
Code = Some "FSAC0004"
Severity = Some DiagnosticSeverity.Hint
Source = Some "FSAC"
Message = "Parentheses can be removed"
RelatedInformation = Some [||]
Tags = Some [| DiagnosticTag.Unnecessary |]
Data = None
CodeDescription = None })
diagnosticCollections.SetFor(uri, "F# unnecessary parentheses", version, diags)
// | NotificationEvent.Lint (file, warnings) ->
// let uri = Path.LocalPathToUri file
// // let fs =
// // warnings |> List.choose (fun w ->
// // w.Warning.Details.SuggestedFix
// // |> Option.bind (fun f ->
// // let f = f.Force()
// // let range = fcsRangeToLsp w.Warning.Details.Range
// // f |> Option.map (fun f -> range, {Range = range; NewText = f.ToText})
// // )
// // )
// let diags =
// warnings
// |> List.map(fun w ->
// let range = fcsRangeToLsp w.Warning.Details.Range
// let fixes =
// match w.Warning.Details.SuggestedFix with
// | None -> None
// | Some lazyFix ->
// match lazyFix.Value with
// | None -> None
// | Some fix ->
// Some (box [ { Range = fcsRangeToLsp fix.FromRange; NewText = fix.ToText } ] )
// let uri = Option.ofObj w.HelpUrl |> Option.map (fun url -> { Href = Some (Uri url) })
// { Range = range
// Code = Some w.Code
// Severity = Some DiagnosticSeverity.Information
// Source = "F# Linter"
// Message = w.Warning.Details.Message
// RelatedInformation = None
// Tags = None
// Data = fixes
// CodeDescription = uri }
// )
// |> List.sortBy (fun diag -> diag.Range)
// |> List.toArray
// diagnosticCollections.SetFor(uri, "F# Linter", diags)
| NotificationEvent.Canceled(msg) ->
let ntf: PlainNotification = { Content = msg }
do! lspClient.NotifyCancelledRequest ntf
| NotificationEvent.AnalyzerMessage(messages, file, version) ->
let uri = Path.LocalPathToUri file
match messages with
| [||] -> diagnosticCollections.SetFor(uri, "F# Analyzers", version, [||])
| messages ->
let diags =
messages
|> Array.map (fun m ->
let range = fcsRangeToLsp m.Range
let severity =
match m.Severity with
| FSharp.Analyzers.SDK.Severity.Hint -> DiagnosticSeverity.Hint
| FSharp.Analyzers.SDK.Severity.Info -> DiagnosticSeverity.Information
| FSharp.Analyzers.SDK.Severity.Warning -> DiagnosticSeverity.Warning
| FSharp.Analyzers.SDK.Severity.Error -> DiagnosticSeverity.Error
let fixes =
match m.Fixes with
| [] -> None
| fixes ->
fixes
|> List.map (fun fix ->
{ Range = fcsRangeToLsp fix.FromRange
NewText = fix.ToText })
|> Ionide.LanguageServerProtocol.Server.serialize
|> Some
{ Range = range
Code = Option.ofObj m.Code
Severity = Some severity
Source = Some $"F# Analyzers (%s{m.Type})"
Message = m.Message
RelatedInformation = None
Tags = None
CodeDescription = None
Data = fixes })
diagnosticCollections.SetFor(uri, "F# Analyzers", version, diags)
| NotificationEvent.TestDetected(file, tests) ->
let rec map
(r: TestAdapter.TestAdapterEntry<FSharp.Compiler.Text.range>)
: TestAdapter.TestAdapterEntry<Ionide.LanguageServerProtocol.Types.Range> =
{ Id = r.Id
List = r.List
Name = r.Name
Type = r.Type
ModuleType = r.ModuleType
Range = fcsRangeToLsp r.Range
Childs = ResizeArray(r.Childs |> Seq.map map) }
do!
{ File = Path.LocalPathToUri file
Tests = tests |> Array.map map }
|> lspClient.NotifyTestDetected
with ex ->
logger.error (
Log.setMessage "Exception while handling command event {evt}: {ex}"
>> Log.addContextDestructured "evt" n
>> Log.addContext "ex" ex.Message
)
()
}
|> fun work -> Async.StartImmediate(work, ct)
with :? OperationCanceledException ->
()
do
disposables.Add(
(notifications.Publish :> IObservable<_>)
// .BufferedDebounce(TimeSpan.FromMilliseconds(200.))
// .SelectMany(fun l -> l.Distinct())
.Subscribe(fun e -> handleCommandEvents e)
)
let getLastUTCChangeForFile (filePath: string<LocalPath>) =
AdaptiveFile.GetLastWriteTimeUtc(UMX.untag filePath)
|> AVal.map (fun writeTime -> filePath, writeTime)
let readFileFromDisk lastTouched (file: string<LocalPath>) =
async {
if File.Exists(UMX.untag file) then
use s = File.openFileStreamForReadingAsync file
let! source = sourceTextFactory.Create(file, s) |> Async.AwaitCancellableValueTask
return
{ LastTouched = lastTouched
Source = source
Version = 0 }
else // When a user does "File -> New Text File -> Select a language -> F#" without saving, the file won't exist
return
{ LastTouched = DateTime.UtcNow
Source = sourceTextFactory.Create(file, "")
Version = 0 }
}
let getLatestFileChange (filePath: string<LocalPath>) =
asyncAVal {
let! (_, lastTouched) = getLastUTCChangeForFile filePath
return! readFileFromDisk lastTouched filePath
}
let addAValLogging cb (aval: aval<_>) =
let cb = aval.AddWeakMarkingCallback(cb)
aval |> AVal.mapDisposableTuple (fun x -> x, cb)
let projectFileChanges project (filePath: string<LocalPath>) =
let file = getLastUTCChangeForFile filePath
let logMsg () =
logger.info (Log.setMessageI $"Loading {project:project} because of {filePath:filePath}")
file |> addAValLogging logMsg
let loader = cval<Ionide.ProjInfo.IWorkspaceLoader> workspaceLoader
let binlogConfig =
aval {
let! generateBinLog = config |> AVal.map (fun c -> c.GenerateBinlog)
and! rootPath = rootPath
match generateBinLog, rootPath with
| _, None
| false, _ -> return Ionide.ProjInfo.BinaryLogGeneration.Off
| true, Some rootPath ->
return Ionide.ProjInfo.BinaryLogGeneration.Within(DirectoryInfo(Path.Combine(rootPath, ".ionide")))
}
let workspacePaths: ChangeableValue<WorkspaceChosen> =
cval WorkspaceChosen.NotChosen
let noopDisposable =
{ new IDisposable with
member this.Dispose() : unit = () }
let adaptiveWorkspacePaths =
workspacePaths
|> AVal.map (fun wsp ->
match wsp with
| WorkspaceChosen.Projs projs ->
let projChanges =
projs
|> ASet.ofSeq
|> ASet.mapAtoAMap (UMX.untag >> AdaptiveFile.GetLastWriteTimeUtc)
let cb =
projChanges.AddWeakCallback(fun _old delta ->
logger.info (
Log.setMessage "Loading projects because of {delta}"
>> Log.addContextDestructured "delta" delta
))
projChanges |> AdaptiveWorkspaceChosen.Projs, cb
| WorkspaceChosen.NotChosen -> AdaptiveWorkspaceChosen.NotChosen, noopDisposable
)
|> AVal.mapDisposableTuple (id)
let clientCapabilities = cval<ClientCapabilities option> None
let glyphToCompletionKind =
clientCapabilities |> AVal.map (glyphToCompletionKindGenerator)
let glyphToSymbolKind = clientCapabilities |> AVal.map glyphToSymbolKindGenerator
let tryFindProp name (props: list<Types.Property>) =
match props |> Seq.tryFind (fun x -> x.Name = name) with
| Some v -> v.Value |> Option.ofObj
| None -> None
let (|ProjectAssetsFile|_|) (props: list<Types.Property>) = tryFindProp "ProjectAssetsFile" props
let (|BaseIntermediateOutputPath|_|) (props: list<Types.Property>) = tryFindProp "BaseIntermediateOutputPath" props
let (|MSBuildAllProjects|_|) (props: list<Types.Property>) =
tryFindProp "MSBuildAllProjects" props
|> Option.map (fun v -> v.Split(';', StringSplitOptions.RemoveEmptyEntries))
let loadedProjectOptions =
aval {
let! loader = loader
and! wsp = adaptiveWorkspacePaths
match wsp with
| AdaptiveWorkspaceChosen.NotChosen -> return []
| AdaptiveWorkspaceChosen.Projs projects ->
let! binlogConfig = binlogConfig
let! projectOptions =
projects
|> AMap.mapWithAdditionalDependencies (fun projects ->
projects
|> Seq.iter (fun (proj: string<LocalPath>, _) ->
let not =
UMX.untag proj |> ProjectResponse.ProjectLoading |> NotificationEvent.Workspace
notifications.Trigger(not, CancellationToken.None))
use progressReport = new ServerProgressReport(lspClient)
progressReport.Begin ($"Loading {projects.Count} Projects") (CancellationToken.None)
|> ignore<Task<unit>>
let projectOptions =
loader.LoadProjects(projects |> Seq.map (fst >> UMX.untag) |> Seq.toList, [], binlogConfig)
|> Seq.toList
for p in projectOptions do
logger.info (
Log.setMessage "Found BaseIntermediateOutputPath of {path}"
>> Log.addContextDestructured "path" ((|BaseIntermediateOutputPath|_|) p.Properties)
)
// Collect other files that should trigger a reload of a project
let additionalDependencies (p: Types.ProjectOptions) =
[ let projectFileChanges = projectFileChanges p.ProjectFileName
match p.Properties with
| ProjectAssetsFile v -> yield projectFileChanges (UMX.tag v)
| _ -> ()
let objPath = (|BaseIntermediateOutputPath|_|) p.Properties
let isWithinObjFolder (file: string) =
match objPath with
| None -> true // if no obj folder provided assume we should track this file
| Some objPath -> file.Contains(objPath)
match p.Properties with
| MSBuildAllProjects v ->
yield!
v
|> Array.choose (fun x ->
if x.EndsWith(".props", StringComparison.Ordinal) && isWithinObjFolder x then
UMX.tag x |> projectFileChanges |> Some
else
None)
| _ -> () ]
HashMap.ofList
[ for p in projectOptions do
UMX.tag p.ProjectFileName, (p, additionalDependencies p) ]
)
|> AMap.toAVal
|> AVal.map HashMap.toValueList
and! checker = checker
checker.ClearCaches() // if we got new projects assume we're gonna need to clear caches
let options =
let fsharpOptions = projectOptions |> FCS.mapManyOptions |> Seq.toList
List.zip projectOptions fsharpOptions
|> List.map (fun (projectOption, fso) ->
let langversion = LanguageVersionShim.fromFSharpProjectOptions fso
// Set some default values as FCS uses these for identification/caching purposes
let fso =
{ fso with
SourceFiles = fso.SourceFiles |> Array.map (Utils.normalizePath >> UMX.untag)
Stamp = fso.Stamp |> Option.orElse (Some DateTime.UtcNow.Ticks)
ProjectId = fso.ProjectId |> Option.orElse (Some(Guid.NewGuid().ToString())) }
{ FSharpProjectOptions = fso
LanguageVersion = langversion },
projectOption)
options
|> List.iter (fun (loadedProject, projectOption) ->
let projectFileName = loadedProject.ProjectFileName
let projViewerItemsNormalized = ProjectViewer.render projectOption
let responseFiles =
projViewerItemsNormalized.Items
|> List.map (function
| ProjectViewerItem.Compile(p, c) -> ProjectViewerItem.Compile(Helpers.fullPathNormalized p, c))
|> List.choose (function
| ProjectViewerItem.Compile(p, _) -> Some p)
let references =
FscArguments.references (loadedProject.FSharpProjectOptions.OtherOptions |> List.ofArray)
logger.info (
Log.setMessage "ProjectLoaded {file}"
>> Log.addContextDestructured "file" projectFileName
)
let ws =
{ ProjectFileName = projectFileName
ProjectFiles = responseFiles
OutFileOpt = Option.ofObj projectOption.TargetPath
References = references
Extra = projectOption
ProjectItems = projViewerItemsNormalized.Items
Additionals = Map.empty }
let not = ProjectResponse.Project(ws, false) |> NotificationEvent.Workspace
notifications.Trigger(not, CancellationToken.None))
let not = ProjectResponse.WorkspaceLoad true |> NotificationEvent.Workspace
notifications.Trigger(not, CancellationToken.None)
return options |> List.map fst
}
/// <summary>
/// Evaluates the adaptive value <see cref='F:loadedProjectOptions '/> and returns its current value.
/// This should not be used inside the adaptive evaluation of other AdaptiveObjects since it does not track dependencies.
/// </summary>
/// <returns>A list of FSharpProjectOptions</returns>
let forceLoadProjects () = loadedProjectOptions |> AVal.force
do
// Reload Projects with some debouncing if `loadedProjectOptions` is out of date.
AVal.Observable.onOutOfDateWeak loadedProjectOptions
|> Observable.throttleOn Concurrency.NewThreadScheduler.Default (TimeSpan.FromMilliseconds(200.))
|> Observable.observeOn Concurrency.NewThreadScheduler.Default
|> Observable.subscribe (fun _ -> forceLoadProjects () |> ignore<list<LoadedProject>>)
|> disposables.Add
let sourceFileToProjectOptions =
aval {
let! options = loadedProjectOptions
return
options
|> List.collect (fun proj ->
proj.SourceFiles
|> Array.map (fun source -> Utils.normalizePath source, proj)
|> Array.toList)
|> List.groupByFst
}
|> AMap.ofAVal
let openFilesTokens =
ConcurrentDictionary<string<LocalPath>, CancellationTokenSource>()
let tryGetOpenFileToken filePath =
match openFilesTokens.TryGetValue(filePath) with
| (true, v) -> Some v
| _ -> None
let getOpenFileTokenOrDefault filePath =
match tryGetOpenFileToken filePath with
| Some v -> v.Token
| None -> CancellationToken.None
let openFiles = cmap<string<LocalPath>, cval<VolatileFile>> ()
let openFilesReadOnly = openFiles |> AMap.map (fun _ x -> x :> aval<_>)
let textChanges =
cmap<string<LocalPath>, cset<DidChangeTextDocumentParams * DateTime>> ()
let textChangesReadOnly = textChanges |> AMap.map (fun _ x -> x :> aset<_>)
let logTextChange (v: VolatileFile) =
logger.debug (
Log.setMessage "TextChanged for file : {fileName} {touched} {version}"
>> Log.addContextDestructured "fileName" v.FileName
>> Log.addContextDestructured "touched" v.LastTouched
>> Log.addContextDestructured "version" v.Version
)
let openFilesWithChanges: amap<_, aval<VolatileFile>> =
openFilesReadOnly
|> AMap.map (fun filePath file ->
aval {
let! file = file
and! changes = textChangesReadOnly |> AMap.tryFind filePath
match changes with
| None -> return file
| Some c ->
let! ps = c |> ASet.toAVal
let changes =
ps
|> Seq.sortBy (fun (x, _) -> x.TextDocument.Version)