back to the school
SageFs.FsiHost/FcsQueries.fs
1 /// The compiler-service queries the isolated host answers (diagnostics, symbol references, completion
2 /// candidates). Compiled ONLY into the host, against the SDK's own FSharp.Compiler.Service, and returning wire
3 /// types from FsiProtocol: no FCS object ever crosses the process boundary, and SageFs needs no FCS to ask.
4 module SageFs.FsiHost.FcsQueries
5
6 open System
7 open FSharp.Compiler.CodeAnalysis
8 open FSharp.Compiler.Diagnostics
9 open FSharp.Compiler.EditorServices
10 open FSharp.Compiler.Interactive.Shell
11 open Microsoft.FSharp.Reflection
12 open SageFs
13 open SageFs.FsiHost.FsiProtocol
14
15 let private severityOf (severity: FSharpDiagnosticSeverity) : DiagnosticSeverity =
16 match severity with
17 | FSharpDiagnosticSeverity.Hidden -> DiagHidden
18 | FSharpDiagnosticSeverity.Info -> DiagInfo
19 | FSharpDiagnosticSeverity.Warning -> DiagWarning
20 | FSharpDiagnosticSeverity.Error -> DiagError
21
22 let toWire (d: FSharpDiagnostic) : FsiDiagnostic =
23 { Severity = severityOf d.Severity
24 ErrorNumber = d.ErrorNumber
25 Subcategory = d.Subcategory
26 Message = d.Message
27 StartLine = d.StartLine
28 StartColumn = d.StartColumn
29 EndLine = d.EndLine
30 EndColumn = d.EndColumn }
31
32 /// All diagnostics of a parse + check, in the same order and de-duplicated the same way SageFs reports them in-process.
33 let private diagnosticsOf (parse: FSharpParseFileResults) (typed: FSharpCheckFileResults) (glob: FSharpCheckProjectResults) =
34 parse.Diagnostics
35 |> Seq.append typed.Diagnostics
36 |> Seq.append glob.Diagnostics
37 |> Seq.map toWire
38 |> Seq.distinct
39 |> Seq.toList
40
41 let check (session: FsiEvaluationSession) (text: string) : FsiDiagnostic list =
42 let parse, typed, glob = session.ParseAndCheckInteraction text
43 diagnosticsOf parse typed glob
44
45 /// Diagnostics plus, for error-free code, every symbol definition and use (opens excluded): the live-testing
46 /// dependency graph's input.
47 let checkWithSymbols (session: FsiEvaluationSession) (filePath: string) (text: string) : FsiDiagnostic list * WireSymbolRef list =
48 let parse, typed, glob = session.ParseAndCheckInteraction text
49 let diagnostics = diagnosticsOf parse typed glob
50 let hasErrors = diagnostics |> List.exists (fun d -> d.Severity = DiagError)
51 let symbols =
52 match hasErrors with
53 | true -> []
54 | false ->
55 typed.GetAllUsesOfAllSymbolsInFile()
56 |> Seq.choose (fun symbolUse ->
57 match symbolUse.IsFromOpenStatement with
58 | true -> None
59 | false ->
60 Some
61 { SymbolFullName = symbolUse.Symbol.FullName
62 Use = (if symbolUse.IsFromDefinition then WireDefinition else WireUsage)
63 FilePath = filePath
64 Line = symbolUse.Range.StartLine })
65 |> Seq.toList
66 diagnostics, symbols
67
68 /// Evaluate a config.fsx expression in this session and hand back the DirectoryConfig it builds. The script's
69 /// `DirectoryConfig.empty` / `LoadStrategy` come from this host's own assembly (ConfigDsl.fs), so the value is the
70 /// real thing, and the daemon never runs the user's script.
71 let evalConfig (session: FsiEvaluationSession) (content: string) : ConfigOutcome =
72 try
73 session.EvalInteractionNonThrowing "open SageFs;;" |> ignore
74 let result, diagnostics = session.EvalExpressionNonThrowing content
75 let errors = diagnostics |> Array.filter (fun d -> d.Severity = FSharpDiagnosticSeverity.Error)
76 match errors.Length > 0 with
77 | true -> ConfigRejected(ConfigDoesNotCompile(errors |> Array.map toWire |> Array.toList))
78 | false ->
79 match result with
80 | Choice1Of2(Some value) ->
81 match value.ReflectionValue with
82 | :? DirectoryConfig as config -> ConfigEvaluated config
83 | null -> ConfigRejected(ConfigWrongType "null")
84 | other -> ConfigRejected(ConfigWrongType(other.GetType().Name))
85 | Choice1Of2 None -> ConfigRejected ConfigNoValue
86 | Choice2Of2 ex -> ConfigRejected(ConfigThrew ex.Message)
87 with ex -> ConfigRejected(ConfigThrew ex.Message)
88
89 /// The completion candidates at the caret, kept as FCS items so a description can be produced on demand.
90 let candidates (session: FsiEvaluationSession) (text: string) (caret: int) : Result<DeclarationListItem[], CompletionFailure> =
91 try
92 let partialName = QuickParse.GetPartialLongNameEx(text, caret - 1)
93 let parse, typed, _ = session.ParseAndCheckInteraction text
94 let listing = typed.GetDeclarationListInfo(Some parse, 1, text, partialName)
95 // On an error FCS hands back one `<Note>` item flagged IsError. That is a refusal to list, not a member.
96 match listing.IsError with
97 | true -> Result.Error ListingFlaggedError
98 | false -> Result.Ok listing.Items
99 with ex ->
100 Result.Error(CheckRaised ex.Message)
101
102 /// FCS's own name for a glyph, read from the type (no hand-written strings): SageFs maps it back by name.
103 let private glyphName (glyph: FSharpGlyph) : string =
104 let case, _ = FSharpValue.GetUnionFields(box glyph, typeof<FSharpGlyph>)
105 case.Name
106
107 let toCompletion (item: DeclarationListItem) : WireCompletion =
108 { DisplayText = item.NameInList
109 ReplacementText = item.NameInCode
110 Glyph = glyphName item.Glyph }
111
112 /// The plain text of a tooltip's main description. THE ONE API-drift seam of this file: the property's type changed
113 /// between SDKs (a TaggedText[] on SDK 10, a RichText on SDK 11), and both expose a `Text` — so it is read through
114 /// that, by shape, and the same source compiles against every SDK's FSharp.Compiler.Service.
115 let private textOf (description: obj) : string =
116 let textProperty (value: obj) =
117 match value.GetType().GetProperty "Text" with
118 | null -> ""
119 | property ->
120 match property.GetValue value with
121 | :? string as text -> text
122 | _ -> ""
123 match description with
124 | null -> ""
125 | :? System.Collections.IEnumerable as parts -> parts |> Seq.cast<obj> |> Seq.map textProperty |> String.concat ""
126 | single -> textProperty single
127
128 /// The first description group's main text, as plain text.
129 let describe (item: DeclarationListItem) : string =
130 item.Description
131 |> (fun (ToolTipText elements) -> elements)
132 |> Seq.collect (function
133 | ToolTipElement.Group group -> group
134 | _ -> [])
135 |> Seq.tryHead
136 |> Option.map (fun element -> textOf (box element.MainDescription))
137 |> Option.defaultValue ""
138