-
Notifications
You must be signed in to change notification settings - Fork 1
/
deopletefs.fsx
395 lines (305 loc) · 14.6 KB
/
deopletefs.fsx
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
// ===========================================================================
// FILE : deopletefs.fsx
// AUTHOR : callmekohei <callmekohei at gmail.com>
// License : MIT license
// Respect : Don Syme : https://github.com/fsharp/FSharp.Compiler.Service/blob/master/fcs/samples/EditorService/Program.fs
// Respect : Tomas Petricek : https://github.com/fsharp/zarchive-fsharpbinding/blob/master/FSharp.AutoComplete/Program.fs
// : https://github.com/fsharp/zarchive-fsharpbinding/blob/master/FSharp.CompilerBinding/LanguageService.fs
// Respect : Japanese F#er : https://gitter.im/fsugjp/public
// ===========================================================================
namespace deopletefs
open System
open System.Collections.Concurrent
open System.Diagnostics
open System.Text.RegularExpressions
#load @"../.paket/load/netcoreapp3.0/main.group.fsx"
open FSharp.Compiler
open FSharp.Compiler.SourceCodeServices
open FSharp.Compiler.QuickParse
open FSharp.Compiler.Text
open Newtonsoft.Json
type PostData = { mutable Row:int; Col:int; mutable Line:string; FilePath:string; Source:string; Init:string }
type JsonFormat = { word : string; info: string list list }
module ServiceSettings =
let internal getEnvInteger e dflt = match System.Environment.GetEnvironmentVariable(e) with null -> dflt | t -> try int t with _ -> dflt
let blockingTimeout = getEnvInteger "FSharpBinding_BlockingTimeout" 500
let maximumTimeout = getEnvInteger "FSharpBinding_MaxTimeout" 5000
type LanguageAgent(dirtyNotify) =
let fakeDateTimeRepresentingTimeLoaded proj = DateTime(abs (int64 (match proj with null -> 0 | _ -> proj.GetHashCode())) % 103231L)
let checker =
let checker = FSharpChecker.Create()
checker.BeforeBackgroundFileCheck.Add dirtyNotify
checker
let parseWithTypeInfo (file, input) =
let checkOptions, _errors = checker.GetProjectOptionsFromScript(file, input) |> Async.RunSynchronously
let parsingOptions, _errors = checker.GetParsingOptionsFromProjectOptions(checkOptions)
let untypedRes = checker.ParseFile(file, input, parsingOptions) |> Async.RunSynchronously
match checker.CheckFileInProject(untypedRes, file, 0, input, checkOptions) |> Async.RunSynchronously with
| FSharpCheckFileAnswer.Succeeded(res) -> untypedRes, res
| res -> failwithf "Parsing did not finish... (%A)" res
let getDecls (postData:PostData, partialName) = async {
let untyped, parsed = parseWithTypeInfo (postData.FilePath, SourceText.ofString postData.Source)
return! parsed.GetDeclarationListInfo(Some untyped, postData.Row, postData.Line, partialName, (fun () -> []))
}
let mbox = MailboxProcessor.Start(fun mbox ->
async {
while true do
let! (postData, partialName, checkOptions, reply: AsyncReplyChannel<_> ) = mbox.Receive()
let blockingTimeout_ms = if postData.Init = "true" then ServiceSettings.maximumTimeout else ServiceSettings.blockingTimeout
let results =
try
Async.RunSynchronously (
getDecls( postData, partialName )
, timeout = blockingTimeout_ms
)
|> fun x -> Some x.Items
with e ->
None
reply.Reply results
}
)
member x.GetCheckerOptions( postData ) =
Async.RunSynchronously (
checker.GetProjectOptionsFromScript( postData.FilePath, SourceText.ofString postData.Source, fakeDateTimeRepresentingTimeLoaded postData.FilePath)
, timeout = ServiceSettings.maximumTimeout
)
member x.GetDeclaration( postData, partialName ) =
async {
let opts = x.GetCheckerOptions( postData )
return! mbox.PostAndAsyncReply(fun reply -> postData, partialName, fst(opts), reply)
}
type PrinterAgent() =
let inbox = MailboxProcessor.Start( fun inbox ->
let rec loop () = async {
let! ( msg : Choice< string , AsyncReplyChannel<unit> > ) = inbox.Receive()
match msg with
| Choice1Of2 (s:string) ->
stdout.WriteLine(s)
return! loop ()
| Choice2Of2 (ch : AsyncReplyChannel<unit>) -> ch.Reply ()
}
loop ()
)
member x.WriteLine(s) = inbox.Post (Choice1Of2 s )
member x.Quit() = inbox.PostAndReply(fun ch -> Choice2Of2 ch)
module Util =
let encode64 (s:string) =
System.Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes( s ) )
let decode64 (base64String:string) =
System.Text.Encoding.UTF8.GetString( System.Convert.FromBase64String( base64String ) )
let angleBracket ( s:string ) :string =
s.Split([|'<';'>'|])
|> Array.filter ( fun s -> s <> "" )
|> fun arr ->
if Array.last arr = "." then
Array.head arr
else
(Array.tail arr).[0]
let nameSpaceArrayImpl ( s:string) :string array =
s.Split('.')
|> Array.filter ( fun s -> s <> "" )
|> fun arr ->
if Array.last arr = "" then
Array.splitAt (arr.Length - 1) arr |> fst
else
arr
let nameSpaceArray (s:string) : string array =
s
|> fun s -> s.Split(' ')
|> Array.filter ( fun s -> s <> "" )
|> Array.last
|> fun ( s:string) ->
if s.Contains("<") then
angleBracket s |> nameSpaceArrayImpl
elif s.Contains(".") then
nameSpaceArrayImpl s
else
[|s|]
|> Array.map( fun s -> s.Replace("(","").Replace(")","") )
let previousDot (s:string) =
s.Split('.')
|> fun arr -> Array.splitAt (Array.length arr - 1 ) arr
|> fst
|> Array.reduce ( fun a b -> a + "." + b )
|> fun s -> s + "."
// https://github.com/fsharp/FSharp.Compiler.Service/blob/master/src/fsharp/symbols/SymbolHelpers.fs#L232
let extractGroupTexts = function
| FSharpToolTipElement.None -> []
| FSharpToolTipElement.CompositionError s -> [s]
| FSharpToolTipElement.Group (xs:FSharpToolTipElementData<string> list) -> xs |> List.map( fun (x:FSharpToolTipElementData<string>) -> x.MainDescription )
let openCount (s:string) : int =
Regex.Matches(s,"^\s*open", RegexOptions.Multiline).Count
/// printout message to deoplete
let msgForDeoplete (wd:string) : string =
JsonConvert.SerializeObject( { word = wd ; info=[[""]] } )
|> fun s -> encode64 s
module FSharpIntellisence =
open Util
let jsonStrings (agent:LanguageAgent) (postData:PostData) (partialName:PartialLongName) : string =
let x = agent.GetDeclaration( postData, partialName ) |> Async.RunSynchronously
if Option.isNone x then
msgForDeoplete "Parsing did not finish..."
else
x.Value
|> Array.map( fun x -> ( x.Name, match x.DescriptionText with FSharpToolTipText xs -> List.map extractGroupTexts xs ) )
|> Array.sortBy fst
|> Array.fold ( fun acc (a,b) ->
acc + "\n" + JsonConvert.SerializeObject( { word = a ; info = b } : JsonFormat )
) ""
|> fun s -> s.Trim()
|> fun s -> Util.encode64 s
let init (agent:LanguageAgent) (dic:ConcurrentDictionary<string,string>) (postData:PostData) : unit =
dic.GetOrAdd( "filePath" , postData.FilePath ) |> ignore
dic.GetOrAdd( "openCount" , string(openCount(postData.Source)) ) |> ignore
let tmpLine = postData.Line
let tmpRow = postData.Row
let getOrAddDic (label:string) ( line:string) (col:int) =
postData.Line <- line
let partialName = QuickParse.GetPartialLongNameEx(line, col)
dic.GetOrAdd( label, jsonStrings agent postData partialName ) |> ignore
postData.Row <- postData.Source.Split('\n').Length
[
// label line col
// ---------------------------------------------
( "Array" , "Array." , 5 )
( "List" , "List." , 4 )
( "Map" , "Map." , 3 )
( "Observable" , "Observable." , 10 )
( "OneWordHint" , "" , 0 )
( "Option" , "Option." , 6 )
( "Seq" , "Seq." , 3 )
( "Set" , "Set." , 3 )
( "System" , "System." , 6 )
( "stderr" , "System.Console.Error." , 20 )
( "stdin" , "System.Console.In." , 17 )
( "stdout" , "System.Console.Out." , 18 )
]
|> List.iter( fun (label,line,col) -> getOrAddDic label line col )
postData.Row <- tmpRow
postData.Line <- tmpLine
let dotHints (agent:LanguageAgent) (dic:ConcurrentDictionary<string,string>) (postData:PostData) : string =
let arr = nameSpaceArray postData.Line
match Array.last arr with
| "Array"
| "List"
| "Map"
| "Observable"
| "Option"
| "Seq"
| "Set"
| "System"
| "stderr"
| "stdin"
| "stdout" ->
dic.Item( Array.last arr )
| _ ->
jsonStrings agent postData (QuickParse.GetPartialLongNameEx(postData.Line, postData.Col))
let oneWordHints (dic:ConcurrentDictionary<string,string>) (str:string) : string =
let s =
if Regex.Match(str,"typeof<.|.*\(.|.*\[.|.*<.|.*:.").Success then
str.Substring( str.Length - 1 )
else
str.Substring(0)
let keyword = """{"word":""" + "\"" + s.ToLower()
dic.Item("OneWordHint")
|> fun s -> Util.decode64 s
|> fun str -> str.Split('\n')
|> Array.filter ( fun str -> str.ToLower().Contains( keyword ) )
|> fun ary ->
if Array.isEmpty ary then
""
|> fun s -> Util.encode64 s
else
ary |> Array.reduce ( fun a b -> a + "\n" + b )
|> fun s -> s.TrimEnd()
|> fun s -> Util.encode64 s
let attributeHints (dic:ConcurrentDictionary<string,string>) : string =
dic.Item( "OneWordHint" )
|> fun s -> Util.decode64 s
|> fun str -> str.Split('\n')
|> Array.filter ( fun str -> str.Contains("Attribute") )
|> Array.reduce ( fun a b -> a + "\n" + b )
|> fun s -> s.TrimEnd()
|> fun s -> Util.encode64 s
let oneWordOrAttributeHints (dic:ConcurrentDictionary<string,string>) (postData:PostData) : string =
postData.Line.Split(' ')
|> Array.filter ( fun s -> s <> "" )
|> fun ary ->
if Array.contains "[<" ary && not ( Array.contains ">]" ary ) then
attributeHints dic
else
oneWordHints dic ( Array.last ary )
let autocomplete (s:string) (agent:LanguageAgent) ( dic :ConcurrentDictionary<string,string> ) : string =
let postData = JsonConvert.DeserializeObject<PostData>(s)
let tryUpdateDic (label:string) ( line:string) (col:int) =
postData.Line <- line
let partialName = QuickParse.GetPartialLongNameEx(line, col)
dic.TryUpdate( label, jsonStrings agent postData partialName, dic.Item(label) ) |> ignore
// update dictionary when open keyword appears.
let updateOpenKeyword () =
if ( openCount( postData.Line ) < 1 ) && ( int(dic.Item("openCount")) <> openCount( postData.Source ) ) then
Debug.WriteLine("changed!")
let tmpLine = postData.Line
let tmpRow = postData.Row
postData.Row <- postData.Source.Split('\n').Length
dic.TryUpdate( "openCount", string( openCount( postData.Source )), dic.Item("openCount") ) |> ignore
[ ("OneWordHint","",0);("System","System.",6);("Observable","Observable.",10)]
|> List.iter( fun (label,line,col) -> tryUpdateDic label line col )
postData.Row <- tmpRow
postData.Line <- tmpLine
let main () =
// For Windows
// System.Threading.Thread.Sleep(25)
updateOpenKeyword ()
let s = postData.Line.Replace("("," ").Split(' ')
|> Array.filter ( fun s -> s <> "" )
|> Array.last
/// . .. ... .... List.. List... List....
if s.StartsWith(".") || (Regex.Match(s,"^.*\.\.+?$")).Success then
msgForDeoplete ""
else
if s.Contains(".") then
if s.EndsWith(".") then
let s = dotHints agent dic postData
Debug.Print("==============================")
Debug.Print(s)
s
else
postData.Line <- previousDot( s )
let s = dotHints agent dic postData
Debug.Print("==============================")
Debug.Print(s)
s
else
let s = oneWordOrAttributeHints dic postData
Debug.Print("==============================")
Debug.Print(s)
s
if postData.Init = "true" then
Debug.WriteLine("===== initialize depletefs =====")
init agent dic postData
msgForDeoplete "finish initialize!"
else
main ()
module InteractiveConsole =
open Util
open FSharpIntellisence
#if DEBUG
let listener = new DefaultTraceListener()
let parentDic = System.Reflection.Assembly.GetEntryAssembly().Location |> fun x -> string ( System.IO.Directory.GetParent(x) )
listener.LogFileName <- System.IO.Path.Combine( parentDic, "log.txt" )
Debug.Listeners.Add(listener)
#endif
let printer = new PrinterAgent()
let dic : ConcurrentDictionary<string,string> = new ConcurrentDictionary< string, string >()
let agent = new LanguageAgent(fun _ -> () )
let rec main s =
match s with
| "quit" -> printer.Quit()
| "init" -> main ( stdin.ReadLine() )
| _ -> printer.WriteLine(autocomplete s agent dic)
main ( stdin.ReadLine() )
[<EntryPointAttribute>]
let entry arg =
main "init"
0