-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathParseAndCheckResults.fs
More file actions
813 lines (708 loc) · 32.8 KB
/
Copy pathParseAndCheckResults.fs
File metadata and controls
813 lines (708 loc) · 32.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
namespace FsAutoComplete
open FsAutoComplete.Logging
open FsAutoComplete.UntypedAstUtils
open FSharp.Compiler
open FSharp.Compiler.CodeAnalysis
open FSharp.Compiler.EditorServices
open FSharp.Compiler.Text
open FSharp.Compiler.Symbols
open FSharp.Compiler.CodeAnalysis
open FSharp.UMX
open System
open System.IO
open Utils
open FSharp.Compiler.Tokenization
open FSharp.Compiler.Syntax
[<RequireQualifiedAccess>]
type FindDeclarationResult =
| ExternalDeclaration of Decompiler.ExternalContentPosition
| Range of FSharp.Compiler.Text.Range
/// The declaration refers to a file.
| File of string
[<RequireQualifiedAccess>]
module TryGetToolTipEnhancedResult =
type SymbolInfo =
| Keyword of string
| Symbol of
{| XmlDocSig: string
Assembly: string |}
type TryGetToolTipEnhancedResult =
{ ToolTipText: ToolTipText
Signature: string
Footer: string
SymbolInfo: TryGetToolTipEnhancedResult.SymbolInfo }
type ParseAndCheckResults
(parseResults: FSharpParseFileResults, checkResults: FSharpCheckFileResults, entityCache: EntityCache) =
let logger = LogProvider.getLoggerByName "ParseAndCheckResults"
let getAllEntitiesUncached (publicOnly: bool) : AssemblySymbol list =
try
[ yield!
AssemblyContent.GetAssemblySignatureContent AssemblyContentType.Full checkResults.PartialAssemblySignature
let ctx = checkResults.ProjectContext
let assembliesByFileName =
ctx.GetReferencedAssemblies()
|> List.groupBy (fun asm -> asm.FileName)
|> List.rev // if mscorlib.dll is the first then FSC raises exception when we try to
// get Content.Entities from it.
for fileName, signatures in assembliesByFileName do
let contentType =
if publicOnly then
AssemblyContentType.Public
else
AssemblyContentType.Full
let content =
AssemblyContent.GetAssemblyContent entityCache.Locking contentType fileName signatures
yield! content ]
with _ ->
[]
let cachedPublicEntities = lazy (getAllEntitiesUncached true)
let cachedFullEntities = lazy (getAllEntitiesUncached false)
let cachedCrefResolver =
lazy (cachedFullEntities.Force() |> TipFormatter.createCrefResolver)
let getFileName (loc: range) =
// Keep the full FCS path, just normalize backslashes to forward slashes.
// FCS may prepend a workspace prefix if the PDB path isn't absolute on this platform.
// The comparison in Sourcelink.compareRepoPath will handle the prefix via suffix matching.
let normalized = loc.FileName.Replace('\\', '/')
UMX.tag<NormalizedRepoPathSegment> normalized
member __.TryFindDeclaration (pos: Position) (lineStr: LineStr) =
async {
// try find identifier first
let! identResult = __.TryFindIdentifierDeclaration pos lineStr
match identResult with
| Ok r -> return Ok r
| Error identErr ->
// then #load directive
let! loadResult = __.TryFindLoadDirectiveSource pos lineStr
match loadResult with
| Ok r -> return Ok r
| Error _ -> return Error identErr
}
member __.TryFindLoadDirectiveSource (pos: Position) (lineStr: LineStr) =
async {
let tryGetFullPath fileName =
try
// use the parsed file name directory as base path
let basePath = Path.GetDirectoryName(UMX.untag __.FileName)
Some(Path.Combine(basePath, fileName))
with
| :? ArgumentException -> None
| :? PathTooLongException -> None
| :? NotSupportedException -> None
let result =
InteractiveDirectives.tryParseLoad lineStr pos.Column
|> Option.bind tryGetFullPath
match result with
| Some file -> return Ok(FindDeclarationResult.File file)
| None -> return Error "load directive not recognized"
}
member x.TryFindIdentifierDeclaration (pos: Position) (lineStr: LineStr) =
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None -> async.Return(ResultOrString.Error "Could not find ident at this location")
| Some(col, identIsland) ->
let identIsland = Array.toList identIsland
let declarations =
checkResults.GetDeclarationLocation(pos.Line, int col, lineStr, identIsland, preferFlag = false)
let decompile assembly externalSym =
match Decompiler.tryFindExternalDeclaration checkResults (assembly, externalSym) with
| Ok extDec -> ResultOrString.Ok(FindDeclarationResult.ExternalDeclaration extDec)
| Error(Decompiler.FindExternalDeclarationError.ReferenceHasNoFileName asm) ->
ResultOrString.Error(sprintf "External declaration assembly '%s' missing file name" asm.SimpleName)
| Error(Decompiler.FindExternalDeclarationError.ReferenceNotFound asm) ->
ResultOrString.Error(sprintf "External declaration assembly '%s' not found" asm)
| Error(Decompiler.FindExternalDeclarationError.DecompileError(Decompiler.Exception(symbol, file, exn))) ->
Error(
sprintf "Error while decompiling symbol '%A' in file '%s': %s\n%s" symbol file exn.Message exn.StackTrace
)
/// these are all None because you can't easily get the source file from the external symbol information here.
let tryGetSourceRangeForSymbol
(sym: FindDeclExternalSymbol)
: (string<NormalizedRepoPathSegment> * Position) option =
match sym with
| FindDeclExternalSymbol.Type _ -> None
| FindDeclExternalSymbol.Constructor _ -> None
| FindDeclExternalSymbol.Method _ -> None
| FindDeclExternalSymbol.Field _ -> None
| FindDeclExternalSymbol.Event _ -> None
| FindDeclExternalSymbol.Property _ -> None
// attempts to manually discover symbol use and external symbol information for a range that doesn't exist in a local file
// bugfix/workaround for FCS returning invalid decl found for f# members.
let tryRecoverExternalSymbolForNonexistentDecl
(rangeInNonexistentFile: FSharp.Compiler.Text.Range)
: ResultOrString<string<LocalPath> * string<NormalizedRepoPathSegment>> =
match Lexer.findLongIdents (uint32 (pos.Column - 1), lineStr) with
| None ->
ResultOrString.Error(
sprintf "Range for nonexistent file found, no ident found: %s" rangeInNonexistentFile.FileName
)
| Some(col, identIsland) ->
let identIsland = Array.toList identIsland
let symbolUse =
checkResults.GetSymbolUseAtLocation(pos.Line, int col, lineStr, identIsland)
match symbolUse with
| None ->
ResultOrString.Error(
sprintf "Range for nonexistent file found, no symbol use found: %s" rangeInNonexistentFile.FileName
)
| Some sym ->
match sym.Symbol.Assembly.FileName with
| Some fullFilePath -> Ok(Utils.normalizePath fullFilePath, getFileName rangeInNonexistentFile)
| None ->
ResultOrString.Error(
sprintf
"Assembly '%s' declaring symbol '%s' has no location on disk"
sym.Symbol.Assembly.QualifiedName
sym.Symbol.DisplayName
)
async {
match declarations with
| FindDeclResult.DeclNotFound reason ->
let elaboration =
match reason with
| FindDeclFailureReason.NoSourceCode -> "No source code was found for the declaration"
| FindDeclFailureReason.ProvidedMember m ->
sprintf "Go-to-declaration is not available for Type Provider-provided member %s" m
| FindDeclFailureReason.ProvidedType t ->
sprintf "Go-to-declaration is not available from Type Provider-provided type %s" t
| FindDeclFailureReason.Unknown r -> r
return ResultOrString.Error(sprintf "Could not find declaration. %s" elaboration)
| FindDeclResult.DeclFound range when
range.FileName.EndsWith(Range.rangeStartup.FileName, StringComparison.Ordinal)
->
return ResultOrString.Error "Could not find declaration"
| FindDeclResult.DeclFound range when range.FileName = UMX.untag x.FileName ->
// decl in same file
// necessary to get decl in untitled file (-> `File.Exists range.FileName` is false)
logger.info (
Log.setMessage "Got a declResult of {range} in same file"
>> Log.addContextDestructured "range" range
)
return Ok(FindDeclarationResult.Range range)
| FindDeclResult.DeclFound range when System.IO.File.Exists range.FileName ->
let rangeStr = range.ToString()
logger.info (
Log.setMessage "Got a declResult of {range} that supposedly exists"
>> Log.addContextDestructured "range" rangeStr
)
return Ok(FindDeclarationResult.Range range)
| FindDeclResult.DeclFound rangeInNonexistentFile ->
let range = rangeInNonexistentFile.ToString()
logger.warn (
Log.setMessage "Got a declResult of {range} that doesn't exist"
>> Log.addContextDestructured "range" range
)
match tryRecoverExternalSymbolForNonexistentDecl rangeInNonexistentFile with
| Ok(assemblyFile, sourceFile) ->
match! Sourcelink.tryFetchSourcelinkFile assemblyFile sourceFile with
| Ok localFilePath ->
return
ResultOrString.Ok(
FindDeclarationResult.ExternalDeclaration
{ File = UMX.untag localFilePath
Position = rangeInNonexistentFile.Start }
)
| Error reason -> return ResultOrString.Error(sprintf "%A" reason)
| Error e -> return Error e
| FindDeclResult.ExternalDecl(assembly, externalSym) ->
// not enough info on external symbols to get a range-like thing :(
match tryGetSourceRangeForSymbol externalSym with
| Some(sourceFile, pos) ->
match! Sourcelink.tryFetchSourcelinkFile (UMX.tag<LocalPath> assembly) sourceFile with
| Ok localFilePath ->
return
ResultOrString.Ok(
FindDeclarationResult.ExternalDeclaration
{ File = UMX.untag localFilePath
Position = pos }
)
| Error _ ->
logger.info (
Log.setMessage "no sourcelink info for {assembly}, decompiling instead"
>> Log.addContextDestructured "assembly" assembly
)
return decompile assembly externalSym
| None -> return decompile assembly externalSym
}
member __.TryFindTypeDeclaration (pos: Position) (lineStr: LineStr) =
async {
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None -> return Error "Cannot find ident at this location"
| Some(col, identIsland) ->
let identIsland = Array.toList identIsland
let symbol =
checkResults.GetSymbolUseAtLocation(pos.Line, int col, lineStr, identIsland)
match symbol with
| None -> return Error "Cannot find symbol at this location"
| Some sym ->
let tryGetTypeDef (t: FSharpType option) =
t
|> Option.bind (fun t -> if t.HasTypeDefinition then Some t.TypeDefinition else None)
let rec tryGetSource (ty: FSharpEntity option) =
async {
match ty |> Option.map (fun ty -> ty, ty.DeclarationLocation) with
| Some(_, loc) when File.Exists loc.FileName -> return Ok(FindDeclarationResult.Range loc)
| Some(ty, loc) ->
match ty.Assembly.FileName with
| Some dllFile ->
let dllFile = UMX.tag<LocalPath> dllFile
let sourceFile = getFileName loc
let! source = Sourcelink.tryFetchSourcelinkFile dllFile sourceFile
match source with
| Ok localFilePath ->
return
Ok(
FindDeclarationResult.ExternalDeclaration
{ File = UMX.untag localFilePath
Position = loc.Start }
)
| Error _ -> return! tryDecompile ty
| None -> return! tryDecompile ty
| None -> return Error "No type information for the symbol at this location"
}
and tryDecompile (ty: FSharpEntity) =
async {
match ty.TryFullName with
| Some fullName ->
let externalSym = FindDeclExternalSymbol.Type fullName
// from TryFindIdentifierDeclaration
let decompile assembly externalSym =
match Decompiler.tryFindExternalDeclaration checkResults (assembly, externalSym) with
| Ok extDec -> ResultOrString.Ok(FindDeclarationResult.ExternalDeclaration extDec)
| Error(Decompiler.FindExternalDeclarationError.ReferenceHasNoFileName asm) ->
ResultOrString.Error(sprintf "External declaration assembly '%s' missing file name" asm.SimpleName)
| Error(Decompiler.FindExternalDeclarationError.ReferenceNotFound asm) ->
ResultOrString.Error(sprintf "External declaration assembly '%s' not found" asm)
| Error(Decompiler.FindExternalDeclarationError.DecompileError(Decompiler.Exception(symbol, file, exn))) ->
Error(
sprintf
"Error while decompiling symbol '%A' in file '%s': %s\n%s"
symbol
file
exn.Message
exn.StackTrace
)
return decompile ty.Assembly.SimpleName externalSym
| None ->
// might be abbreviated type (like string)
return!
(if ty.IsFSharpAbbreviation then
Some ty.AbbreviatedType
else
None)
|> tryGetTypeDef
|> tryGetSource
}
let ty =
match sym with
| SymbolUse.Field f -> Some f.FieldType |> tryGetTypeDef
| SymbolUse.Constructor c -> c.DeclaringEntity
| SymbolUse.Property p when p.IsPropertyGetterMethod -> Some p.ReturnParameter.Type |> tryGetTypeDef
| SymbolUse.Val v -> v.FullTypeSafe |> tryGetTypeDef
| SymbolUse.Entity(e, _) -> Some e
| SymbolUse.UnionCase c -> Some c.ReturnType |> tryGetTypeDef
| SymbolUse.Parameter p -> Some p.Type |> tryGetTypeDef
| _ -> None
return! tryGetSource ty
}
member __.TryGetToolTip (pos: Position) (lineStr: LineStr) =
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None ->
logger.info (Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}")
None
| Some(col, identIsland) ->
let identIsland = Array.toList identIsland
// TODO: Display other tooltip types, for example for strings or comments where appropriate
let tip =
checkResults.GetToolTip(pos.Line, int col, lineStr, identIsland, FSharpTokenTag.Identifier)
match tip with
| ToolTipText(elems) when elems |> List.forall ((=) ToolTipElement.None) ->
match identIsland with
| [ ident ] ->
match KeywordList.keywordTooltips.TryGetValue ident with
| true, tip -> Some tip
| _ ->
logger.info (Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}")
None
| _ ->
logger.info (Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}")
None
| _ -> Some tip
member x.TryGetToolTipEnhanced (pos: Position) (lineStr: LineStr) : option<TryGetToolTipEnhancedResult> =
let (|EmptyTooltip|_|) (ToolTipText elems) =
match elems with
| [] -> Some()
| elems when elems |> List.forall ((=) ToolTipElement.None) -> Some()
| _ -> None
match Completion.atPos (pos, x.GetParseResults.ParseTree) with
| Completion.Context.StringLiteral -> None
| Completion.Context.SynType
| Completion.Context.Unknown ->
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None ->
// Check if we're hovering over a hash directive (e.g. #r, #load, #nowarn).
// Lexer.findLongIdents returns None for multi-character directives like #nowarn because
// the F# tokenizer emits them as directive tokens, not plain identifiers.
let trimmedLine = lineStr.TrimStart()
if trimmedLine.StartsWith("#") then
let leadingSpaces = lineStr.Length - trimmedLine.Length
let rest = trimmedLine.Substring(1)
let wordEnd = rest.IndexOfAny([| ' '; '\t'; '"'; '\r'; '\n' |])
let directiveWord = if wordEnd > 0 then rest.[.. wordEnd - 1] else rest
let directiveEndCol = leadingSpaces + 1 + directiveWord.Length
if pos.Column < directiveEndCol then
match KeywordList.hashDirectiveTooltips.TryGetValue directiveWord with
| true, tip ->
{ ToolTipText = tip
Signature = "#" + directiveWord
Footer = ""
SymbolInfo = TryGetToolTipEnhancedResult.Keyword directiveWord }
|> Some
| _ ->
logger.info (
Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}"
)
None
else
logger.info (Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}")
None
else
logger.info (Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}")
None
| Some(col, identIsland) ->
let identIsland = Array.toList identIsland
// TODO: Display other tooltip types, for example for strings or comments where appropriate
let tip =
checkResults.GetToolTip(pos.Line, int col, lineStr, identIsland, FSharpTokenTag.Identifier)
let symbol =
checkResults.GetSymbolUseAtLocation(pos.Line, int col, lineStr, identIsland)
match tip with
| EmptyTooltip when symbol.IsNone ->
match identIsland with
| [ ident ] ->
match KeywordList.keywordTooltips.TryGetValue ident with
| true, tip ->
{ ToolTipText = tip
Signature = ident
Footer = ""
SymbolInfo = TryGetToolTipEnhancedResult.Keyword ident }
|> Some
| _ ->
// Check if we're hovering over a hash directive (e.g., #r, #load, #nowarn)
let trimmedLine = lineStr.TrimStart()
match KeywordList.hashDirectiveTooltips.TryGetValue ident with
| true, tip when trimmedLine.StartsWith("#" + ident) ->
{ ToolTipText = tip
Signature = "#" + ident
Footer = ""
SymbolInfo = TryGetToolTipEnhancedResult.Keyword ident }
|> Some
| _ ->
logger.info (
Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}"
)
None
| _ ->
logger.info (Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}")
None
| _ ->
match symbol with
| None ->
logger.info (Log.setMessageI $"Cannot find ident for tooltip: {pos.Column:column} in {lineStr:lineString}")
None
| Some symbol ->
// Retrieve the FSharpSymbol instance so we can find the XmlDocSig
// This mimic, the behavior of the Info Panel on hover
// 1. If this is a concrete type it returns that type reference
// 2. If this a type alias, it returns the aliases type reference
let resolvedType = symbol.Symbol.GetAbbreviatedParent()
match SignatureFormatter.getTooltipDetailsFromSymbolUse symbol with
| None ->
logger.info (
Log.setMessageI $"Cannot find tooltip for {symbol:symbol} ({pos.Column:column} in {lineStr:lineString})"
)
None
| Some(signature, footer) ->
{ ToolTipText = tip
Signature = signature
Footer = footer
SymbolInfo =
TryGetToolTipEnhancedResult.Symbol
{| XmlDocSig = resolvedType.XmlDocSig
Assembly = symbol.Symbol.Assembly.SimpleName |} }
|> Some
member __.TryGetFormattedDocumentation (pos: Position) (lineStr: LineStr) =
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None -> Error "Cannot find ident"
| Some(col, identIsland) ->
let identIsland = Array.toList identIsland
// TODO: Display other tooltip types, for example for strings or comments where appropriate
let tip =
checkResults.GetToolTip(pos.Line, int col, lineStr, identIsland, FSharpTokenTag.Identifier)
let symbol =
checkResults.GetSymbolUseAtLocation(pos.Line, int col, lineStr, identIsland)
match tip with
| ToolTipText(elems) when elems |> List.forall ((=) ToolTipElement.None) && symbol.IsNone ->
match identIsland with
| [ ident ] ->
match KeywordList.keywordTooltips.TryGetValue ident with
| true, tip -> Ok(Some tip, None, (ident, DocumentationFormatter.EntityInfo.Empty), "", "")
| _ -> Error "No tooltip information"
| _ -> Error "No documentation information"
| _ ->
match symbol with
| None -> Error "No documentation information"
| Some symbol ->
match DocumentationFormatter.getTooltipDetailsFromSymbolUse symbol with
| None -> Error "No documentation information"
| Some(signature, footer, cn) ->
match symbol with
| SymbolUse.TypeAbbreviation symbol ->
Ok(
None,
Some(
symbol.GetAbbreviatedParent().XmlDocSig,
symbol.GetAbbreviatedParent().Assembly.FileName |> Option.defaultValue ""
),
signature,
footer,
cn
)
| _ -> Ok(Some tip, None, signature, footer, cn)
member x.TryGetFormattedDocumentationForSymbol (xmlSig: string) (assembly: string) =
let entities = x.GetAllEntities false
let matchesSymbol includeAssembly (symbol: FSharpSymbol) =
try
symbol.XmlDocSig = xmlSig
&& (not includeAssembly || symbol.Assembly.SimpleName = assembly)
with _ ->
false
let matchesAbbreviatedEntity includeAssembly (symbol: FSharpSymbol) =
match symbol with
| FSharpEntity(_, abrvEnt, _) ->
try
abrvEnt.XmlDocSig = xmlSig
&& (not includeAssembly || abrvEnt.Assembly.SimpleName = assembly)
with _ ->
false
| _ -> false
let ent =
entities
|> List.tryFind (fun e -> matchesSymbol true e.Symbol || matchesAbbreviatedEntity true e.Symbol)
let ent =
match ent with
| Some ent -> Some ent
| None ->
entities
|> List.tryFind (fun e -> matchesSymbol false e.Symbol || matchesAbbreviatedEntity false e.Symbol)
let symbol =
match ent with
| Some ent -> Some ent.Symbol
| None ->
entities
|> List.tryPick (fun e ->
match e.Symbol with
| FSharpEntity(ent, _, _) ->
match
ent.MembersFunctionsAndValues
|> Seq.tryPick (fun f ->
try
if f.XmlDocSig = xmlSig then
Some(f :> FSharpSymbol)
else
None
with _ ->
None)
with
| Some e -> Some e
| None ->
match
ent.FSharpFields
|> Seq.tryPick (fun f ->
try
if f.XmlDocSig = xmlSig then
Some(f :> FSharpSymbol)
else
None
with _ ->
None)
with
| Some e -> Some e
| None ->
ent.UnionCases
|> Seq.tryPick (fun f ->
try
if f.XmlDocSig = xmlSig then
Some(f :> FSharpSymbol)
else
None
with _ ->
None)
| _ -> None)
let symbol =
match symbol with
| Some symbol when matchesSymbol false symbol -> Some symbol
| _ -> None
match symbol with
| None -> Error "No matching symbol information"
| Some symbol ->
match DocumentationFormatter.getTooltipDetailsFromSymbol symbol with
| None -> Error "No tooltip information"
| Some(signature, footer, cn) ->
Ok(symbol.XmlDocSig, symbol.Assembly.FileName |> Option.defaultValue "", symbol.XmlDoc, signature, footer, cn)
member __.TryGetSymbolUse (pos: Position) (lineStr: LineStr) : FSharpSymbolUse option =
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None -> None
| Some(colu, identIsland) ->
let identIsland = Array.toList identIsland
checkResults.GetSymbolUseAtLocation(pos.Line, int colu, lineStr, identIsland)
member x.TryGetSymbolUseFromIdent (sourceText: ISourceText) (ident: Ident) : FSharpSymbolUse option =
let line = sourceText.GetLineString(ident.idRange.EndLine - 1)
x.GetCheckResults.GetSymbolUseAtLocation(ident.idRange.EndLine, ident.idRange.EndColumn, line, [ ident.idText ])
member __.TryGetSymbolUses (pos: Position) (lineStr: LineStr) : FSharpSymbolUse list =
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None -> []
| Some(colu, identIsland) ->
let identIsland = Array.toList identIsland
checkResults.GetSymbolUsesAtLocation(pos.Line, int colu, lineStr, identIsland)
member x.TryGetSymbolUseAndUsages (pos: Position) (lineStr: LineStr) =
let symbolUse = x.TryGetSymbolUse pos lineStr
match symbolUse with
| None -> ResultOrString.Error "No symbol information found"
| Some symbolUse ->
let symbolUses = checkResults.GetUsesOfSymbolInFile symbolUse.Symbol
Ok(symbolUse, symbolUses)
member __.TryGetSignatureData (pos: Position) (lineStr: LineStr) =
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None -> ResultOrString.Error "No ident at this location"
| Some(colu, identIsland) ->
let identIsland = Array.toList identIsland
let symbolUse =
checkResults.GetSymbolUseAtLocation(pos.Line, int colu, lineStr, identIsland)
match symbolUse with
| None -> ResultOrString.Error "No symbol information found"
| Some symbolUse ->
let fsym = symbolUse.Symbol
match fsym with
| :? FSharpMemberOrFunctionOrValue as symbol ->
let typ =
symbol.ReturnParameter.Type.Format(symbolUse.DisplayContext.WithPrefixGenericParameters())
if symbol.IsPropertyGetterMethod then
Ok(typ, [], [])
else
let symbol =
// Symbol is a property with both get and set.
// Take the setter symbol in this case.
if symbol.HasGetterMethod && symbol.HasSetterMethod then
symbol.SetterMethod
else
symbol
let parms =
symbol.CurriedParameterGroups
|> Seq.map (
Seq.map (fun p -> p.DisplayName, p.Type.Format(symbolUse.DisplayContext.WithPrefixGenericParameters()))
>> Seq.toList
)
|> Seq.toList
let generics =
symbol.GenericParameters |> Seq.map (fun generic -> generic.Name) |> Seq.toList
// Abstract members and abstract member overrides with one () parameter seem have a list with an empty list
// as parameters.
match parms with
| [ [] ] when symbol.IsMember && (not symbol.IsPropertyGetterMethod) ->
Ok(typ, [ [ ("unit", "unit") ] ], [])
| _ -> Ok(typ, parms, generics)
| :? FSharpField as symbol ->
let typ = symbol.FieldType.Format symbolUse.DisplayContext
Ok(typ, [], [])
| _ -> ResultOrString.Error "Not a member, function or value"
member __.TryGetF1Help (pos: Position) (lineStr: LineStr) =
match Lexer.findLongIdents (uint32 pos.Column, lineStr) with
| None -> ResultOrString.Error "No ident at this location"
| Some(colu, identIsland) ->
let identIsland = Array.toList identIsland
let help = checkResults.GetF1Keyword(pos.Line, int colu, lineStr, identIsland)
match help with
| None -> ResultOrString.Error "No symbol information found"
| Some hlp -> Ok hlp
member x.TryGetCompletions (pos: Position) (lineStr: LineStr) (getAllSymbols: unit -> AssemblySymbol list) =
async {
let completionContext = Completion.atPos (pos, x.GetParseResults.ParseTree)
match completionContext with
| Completion.Context.StringLiteral -> return None
| Completion.Context.Unknown
| Completion.Context.SynType ->
try
let longName = QuickParse.GetPartialLongNameEx(lineStr, pos.Column - 1)
let getSymbols () =
[ for assemblySymbol in getAllSymbols () do
if
assemblySymbol.FullName.Contains(".")
&& not (PrettyNaming.IsOperatorDisplayName assemblySymbol.Symbol.DisplayName)
then
yield assemblySymbol ]
let fcsCompletionContext =
ParsedInput.TryGetCompletionContext(pos, x.GetParseResults.ParseTree, lineStr)
let results =
checkResults.GetDeclarationListInfo(
Some parseResults,
pos.Line,
lineStr,
longName,
getAllEntities = getSymbols,
completionContextAtPos = (pos, fcsCompletionContext)
)
let getKindPriority kind =
match kind with
| CompletionItemKind.SuggestedName
| CompletionItemKind.CustomOperation -> 0
// Named arguments (constructor/function call context) are the most
// immediately relevant completions — give them the same priority as
// properties so they appear at the top of the list (closes #1500).
| CompletionItemKind.Argument -> 1
| CompletionItemKind.Property -> 1
| CompletionItemKind.Field -> 2
| CompletionItemKind.Method(isExtension = false) -> 3
| CompletionItemKind.Event -> 4
| CompletionItemKind.Other -> 6
| CompletionItemKind.Method(isExtension = true) -> 7
Array.sortInPlaceWith
(fun (x: DeclarationListItem) (y: DeclarationListItem) ->
let mutable n = (not x.IsResolved).CompareTo(not y.IsResolved)
if n <> 0 then
n
else
n <- (getKindPriority x.Kind).CompareTo(getKindPriority y.Kind)
if n <> 0 then
n
else
n <- (not x.IsOwnMember).CompareTo(not y.IsOwnMember)
if n <> 0 then
n
else
n <- String.Compare(x.NameInList, y.NameInList, StringComparison.OrdinalIgnoreCase)
if n <> 0 then
n
else
x.MinorPriority.CompareTo(y.MinorPriority))
results.Items
let shouldKeywords =
results.Items.Length > 0
&& not results.IsForType
&& not results.IsError
&& List.isEmpty longName.QualifyingIdents
return Some(results.Items, longName.PartialIdent, shouldKeywords)
with :? TimeoutException ->
return None
}
member __.GetAllEntities(publicOnly: bool) : AssemblySymbol list =
if publicOnly then
cachedPublicEntities.Force()
else
cachedFullEntities.Force()
member __.GetCrefResolver() = cachedCrefResolver.Force()
member __.GetAllSymbolUsesInFile() = checkResults.GetAllUsesOfAllSymbolsInFile()
member __.GetSemanticClassification = checkResults.GetSemanticClassification None
member __.GetAST = parseResults.ParseTree
member __.GetCheckResults: FSharpCheckFileResults = checkResults
member __.GetParseResults: FSharpParseFileResults = parseResults
member __.FileName: string<LocalPath> = Utils.normalizePath parseResults.FileName