-
Notifications
You must be signed in to change notification settings - Fork 463
/
Copy pathCompletionBackEnd.ml
2341 lines (2274 loc) · 86.5 KB
/
CompletionBackEnd.ml
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
open SharedTypes
let showConstructor {Constructor.cname = {txt}; args; res} =
txt
^ (match args with
| Args [] -> ""
| InlineRecord fields ->
"({"
^ (fields
|> List.map (fun (field : field) ->
Printf.sprintf "%s%s: %s" field.fname.txt
(if field.optional then "?" else "")
(Shared.typeToString
(if field.optional then Utils.unwrapIfOption field.typ
else field.typ)))
|> String.concat ", ")
^ "})"
| Args args ->
"("
^ (args
|> List.map (fun (typ, _) -> typ |> Shared.typeToString)
|> String.concat ", ")
^ ")")
^
match res with
| None -> ""
| Some typ -> "\n" ^ (typ |> Shared.typeToString)
(* TODO: local opens *)
let resolveOpens ~env opens ~package =
List.fold_left
(fun previous path ->
(* Finding an open, first trying to find it in previoulsly resolved opens *)
let rec loop prev =
match prev with
| [] -> (
match path with
| [] | [_] -> previous
| name :: path -> (
match ProcessCmt.fileForModule ~package name with
| None ->
Log.log ("Could not get module " ^ name);
previous (* TODO: warn? *)
| Some file -> (
match
ResolvePath.resolvePath ~env:(QueryEnv.fromFile file) ~package
~path
with
| None ->
Log.log ("Could not resolve in " ^ name);
previous
| Some (env, _placeholder) -> previous @ [env])))
| env :: rest -> (
match ResolvePath.resolvePath ~env ~package ~path with
| None -> loop rest
| Some (env, _placeholder) -> previous @ [env])
in
Log.log ("resolving open " ^ pathToString path);
match ResolvePath.resolvePath ~env ~package ~path with
| None ->
Log.log "Not local";
loop previous
| Some (env, _) ->
Log.log "Was local";
previous @ [env])
(* loop(previous) *)
[] opens
let completionForExporteds iterExported getDeclared ~prefix ~exact ~env
~namesUsed transformContents =
let res = ref [] in
iterExported (fun name stamp ->
(* Log.log("checking exported: " ++ name); *)
if Utils.checkName name ~prefix ~exact then
match getDeclared stamp with
| Some (declared : _ Declared.t)
when not (Hashtbl.mem namesUsed declared.name.txt) ->
Hashtbl.add namesUsed declared.name.txt ();
res :=
{
(Completion.create declared.name.txt ~env
~kind:(transformContents declared))
with
deprecated = declared.deprecated;
docstring = declared.docstring;
}
:: !res
| _ -> ());
!res
let completionForExportedModules ~env ~prefix ~exact ~namesUsed =
completionForExporteds (Exported.iter env.QueryEnv.exported Exported.Module)
(Stamps.findModule env.file.stamps) ~prefix ~exact ~env ~namesUsed
(fun declared ->
Completion.Module
{docstring = declared.docstring; module_ = declared.item})
let completionForExportedValues ~env ~prefix ~exact ~namesUsed =
completionForExporteds (Exported.iter env.QueryEnv.exported Exported.Value)
(Stamps.findValue env.file.stamps) ~prefix ~exact ~env ~namesUsed
(fun declared -> Completion.Value declared.item)
let completionForExportedTypes ~env ~prefix ~exact ~namesUsed =
completionForExporteds (Exported.iter env.QueryEnv.exported Exported.Type)
(Stamps.findType env.file.stamps) ~prefix ~exact ~env ~namesUsed
(fun declared -> Completion.Type declared.item)
let completionsForExportedConstructors ~(env : QueryEnv.t) ~prefix ~exact
~namesUsed =
let res = ref [] in
Exported.iter env.exported Exported.Type (fun _name stamp ->
match Stamps.findType env.file.stamps stamp with
| Some ({item = {kind = Type.Variant constructors}} as t) ->
res :=
(constructors
|> List.filter (fun c ->
Utils.checkName c.Constructor.cname.txt ~prefix ~exact)
|> Utils.filterMap (fun c ->
let name = c.Constructor.cname.txt in
if not (Hashtbl.mem namesUsed name) then
let () = Hashtbl.add namesUsed name () in
Some
(Completion.create name ~env ~docstring:c.docstring
?deprecated:c.deprecated
~kind:
(Completion.Constructor
(c, t.item.decl |> Shared.declToString t.name.txt)))
else None))
@ !res
| _ -> ());
!res
let completionForExportedFields ~(env : QueryEnv.t) ~prefix ~exact ~namesUsed =
let res = ref [] in
Exported.iter env.exported Exported.Type (fun _name stamp ->
match Stamps.findType env.file.stamps stamp with
| Some ({item = {kind = Record fields}} as t) ->
res :=
(fields
|> List.filter (fun f -> Utils.checkName f.fname.txt ~prefix ~exact)
|> Utils.filterMap (fun f ->
let name = f.fname.txt in
if not (Hashtbl.mem namesUsed name) then
let () = Hashtbl.add namesUsed name () in
Some
(Completion.create name ~env ~docstring:f.docstring
?deprecated:f.deprecated
~kind:
(Completion.Field
(f, t.item.decl |> Shared.declToString t.name.txt)))
else None))
@ !res
| _ -> ());
!res
let findModuleInScope ~env ~moduleName ~scope =
let modulesTable = Hashtbl.create 10 in
env.QueryEnv.file.stamps
|> Stamps.iterModules (fun _ declared ->
Hashtbl.replace modulesTable
(declared.name.txt, declared.extentLoc |> Loc.start)
declared);
let result = ref None in
let processModule name loc =
if name = moduleName && !result = None then
match Hashtbl.find_opt modulesTable (name, Loc.start loc) with
| Some declared -> result := Some declared
| None ->
Log.log
(Printf.sprintf "Module Not Found %s loc:%s\n" name (Loc.toString loc))
in
scope |> Scope.iterModulesBeforeFirstOpen processModule;
scope |> Scope.iterModulesAfterFirstOpen processModule;
!result
let resolvePathFromStamps ~(env : QueryEnv.t) ~package ~scope ~moduleName ~path
=
(* Log.log("Finding from stamps " ++ name); *)
match findModuleInScope ~env ~moduleName ~scope with
| None -> None
| Some declared -> (
(* Log.log("found it"); *)
match ResolvePath.findInModule ~env declared.item path with
| None -> None
| Some res -> (
match res with
| `Local (env, name) -> Some (env, name)
| `Global (moduleName, fullPath) -> (
match ProcessCmt.fileForModule ~package moduleName with
| None -> None
| Some file ->
ResolvePath.resolvePath ~env:(QueryEnv.fromFile file) ~path:fullPath
~package)))
let resolveModuleWithOpens ~opens ~package ~moduleName =
let rec loop opens =
match opens with
| (env : QueryEnv.t) :: rest -> (
Log.log ("Looking for env in " ^ Uri.toString env.file.uri);
match ResolvePath.resolvePath ~env ~package ~path:[moduleName; ""] with
| Some (env, _) -> Some env
| None -> loop rest)
| [] -> None
in
loop opens
let resolveFileModule ~moduleName ~package =
Log.log ("Getting module " ^ moduleName);
match ProcessCmt.fileForModule ~package moduleName with
| None -> None
| Some file ->
Log.log "got it";
let env = QueryEnv.fromFile file in
Some env
let getEnvWithOpens ~scope ~(env : QueryEnv.t) ~package
~(opens : QueryEnv.t list) ~moduleName (path : string list) =
(* TODO: handle interleaving of opens and local modules correctly *)
match resolvePathFromStamps ~env ~scope ~moduleName ~path ~package with
| Some x -> Some x
| None -> (
match resolveModuleWithOpens ~opens ~package ~moduleName with
| Some env -> ResolvePath.resolvePath ~env ~package ~path
| None -> (
match resolveFileModule ~moduleName ~package with
| None -> None
| Some env -> ResolvePath.resolvePath ~env ~package ~path))
let rec expandTypeExpr ~env ~package typeExpr =
match typeExpr |> Shared.digConstructor with
| Some path -> (
match References.digConstructor ~env ~package path with
| None -> None
| Some (env, {item = {decl = {type_manifest = Some t}}}) ->
expandTypeExpr ~env ~package t
| Some (_, {docstring; item}) -> Some (docstring, item))
| None -> None
let kindToDocumentation ~env ~full ~currentDocstring name
(kind : Completion.kind) =
let docsFromKind =
match kind with
| ObjLabel _ | Label _ | FileModule _ | Snippet _ | FollowContextPath _ ->
[]
| Module {docstring} -> docstring
| Type {decl; name} ->
[decl |> Shared.declToString name |> Markdown.codeBlock]
| Value typ -> (
match expandTypeExpr ~env ~package:full.package typ with
| None -> []
| Some (docstrings, {decl; name; kind}) ->
docstrings
@ [
(match kind with
| Record _ | Tuple _ | Variant _ ->
Markdown.codeBlock (Shared.declToString name decl)
| _ -> "");
])
| Field ({typ; optional; docstring}, s) ->
(* Handle optional fields. Checking for "?" is because sometimes optional
fields are prefixed with "?" when completing, and at that point we don't
need to _also_ add a "?" after the field name, as that looks weird. *)
docstring
@ [
Markdown.codeBlock
(if optional && Utils.startsWith name "?" = false then
name ^ "?: "
^ (typ |> Utils.unwrapIfOption |> Shared.typeToString)
else name ^ ": " ^ (typ |> Shared.typeToString));
Markdown.codeBlock s;
]
| Constructor (c, s) ->
[Markdown.codeBlock (showConstructor c); Markdown.codeBlock s]
| PolyvariantConstructor ({displayName; args}, s) ->
[
Markdown.codeBlock
("#" ^ displayName
^
match args with
| [] -> ""
| typeExprs ->
"("
^ (typeExprs
|> List.map (fun typeExpr -> typeExpr |> Shared.typeToString)
|> String.concat ", ")
^ ")");
Markdown.codeBlock s;
]
| ExtractedType (extractedType, _) ->
[Markdown.codeBlock (TypeUtils.extractedTypeToString extractedType)]
in
currentDocstring @ docsFromKind
|> List.filter (fun s -> s <> "")
|> String.concat "\n\n"
let kindToDetail name (kind : Completion.kind) =
match kind with
| Type {name} -> "type " ^ name
| Value typ -> typ |> Shared.typeToString
| ObjLabel typ -> typ |> Shared.typeToString
| Label typString -> typString
| Module _ -> "module " ^ name
| FileModule f -> "module " ^ f
| Field ({typ; optional}, _) ->
(* Handle optional fields. Checking for "?" is because sometimes optional
fields are prefixed with "?" when completing, and at that point we don't
need to _also_ add a "?" after the field name, as that looks weird. *)
if optional && Utils.startsWith name "?" = false then
typ |> Utils.unwrapIfOption |> Shared.typeToString
else typ |> Shared.typeToString
| Constructor (c, _) -> showConstructor c
| PolyvariantConstructor ({displayName; args}, _) -> (
"#" ^ displayName
^
match args with
| [] -> ""
| typeExprs ->
"("
^ (typeExprs
|> List.map (fun typeExpr -> typeExpr |> Shared.typeToString)
|> String.concat ", ")
^ ")")
| Snippet s -> s
| FollowContextPath _ -> ""
| ExtractedType (extractedType, _) ->
TypeUtils.extractedTypeToString ~nameOnly:true extractedType
let kindToData filePath (kind : Completion.kind) =
match kind with
| FileModule f -> Some [("modulePath", f); ("filePath", filePath)]
| _ -> None
let findAllCompletions ~(env : QueryEnv.t) ~prefix ~exact ~namesUsed
~(completionContext : Completable.completionContext) =
Log.log ("findAllCompletions uri:" ^ Uri.toString env.file.uri);
match completionContext with
| Value ->
completionForExportedValues ~env ~prefix ~exact ~namesUsed
@ completionsForExportedConstructors ~env ~prefix ~exact ~namesUsed
@ completionForExportedModules ~env ~prefix ~exact ~namesUsed
| Type ->
completionForExportedTypes ~env ~prefix ~exact ~namesUsed
@ completionForExportedModules ~env ~prefix ~exact ~namesUsed
| Module -> completionForExportedModules ~env ~prefix ~exact ~namesUsed
| Field ->
completionForExportedFields ~env ~prefix ~exact ~namesUsed
@ completionForExportedModules ~env ~prefix ~exact ~namesUsed
| ValueOrField ->
completionForExportedValues ~env ~prefix ~exact ~namesUsed
@ completionForExportedFields ~env ~prefix ~exact ~namesUsed
@ completionForExportedModules ~env ~prefix ~exact ~namesUsed
let processLocalValue name loc contextPath scope ~prefix ~exact ~env
~(localTables : LocalTables.t) =
if Utils.checkName name ~prefix ~exact then
match Hashtbl.find_opt localTables.valueTable (name, Loc.start loc) with
| Some declared ->
if not (Hashtbl.mem localTables.namesUsed name) then (
Hashtbl.add localTables.namesUsed name ();
localTables.resultRev <-
{
(Completion.create declared.name.txt ~env ~kind:(Value declared.item))
with
deprecated = declared.deprecated;
docstring = declared.docstring;
}
:: localTables.resultRev)
| None ->
if !Cfg.debugFollowCtxPath then
Printf.printf "Completion Value Not Found %s loc:%s\n" name
(Loc.toString loc);
localTables.resultRev <-
Completion.create name ~env
~kind:
(match contextPath with
| Some contextPath -> FollowContextPath (contextPath, scope)
| None ->
Value
(Ctype.newconstr
(Path.Pident (Ident.create "Type Not Known"))
[]))
:: localTables.resultRev
let processLocalConstructor name loc ~prefix ~exact ~env
~(localTables : LocalTables.t) =
if Utils.checkName name ~prefix ~exact then
match
Hashtbl.find_opt localTables.constructorTable (name, Loc.start loc)
with
| Some declared ->
if not (Hashtbl.mem localTables.namesUsed name) then (
Hashtbl.add localTables.namesUsed name ();
localTables.resultRev <-
{
(Completion.create declared.name.txt ~env
~kind:
(Constructor
( declared.item,
snd declared.item.typeDecl
|> Shared.declToString (fst declared.item.typeDecl) )))
with
deprecated = declared.deprecated;
docstring = declared.docstring;
}
:: localTables.resultRev)
| None ->
Log.log
(Printf.sprintf "Completion Constructor Not Found %s loc:%s\n" name
(Loc.toString loc))
let processLocalType name loc ~prefix ~exact ~env ~(localTables : LocalTables.t)
=
if Utils.checkName name ~prefix ~exact then
match Hashtbl.find_opt localTables.typesTable (name, Loc.start loc) with
| Some declared ->
if not (Hashtbl.mem localTables.namesUsed name) then (
Hashtbl.add localTables.namesUsed name ();
localTables.resultRev <-
{
(Completion.create declared.name.txt ~env ~kind:(Type declared.item))
with
deprecated = declared.deprecated;
docstring = declared.docstring;
}
:: localTables.resultRev)
| None ->
Log.log
(Printf.sprintf "Completion Type Not Found %s loc:%s\n" name
(Loc.toString loc))
let processLocalModule name loc ~prefix ~exact ~env
~(localTables : LocalTables.t) =
if Utils.checkName name ~prefix ~exact then
match Hashtbl.find_opt localTables.modulesTable (name, Loc.start loc) with
| Some declared ->
if not (Hashtbl.mem localTables.namesUsed name) then (
Hashtbl.add localTables.namesUsed name ();
localTables.resultRev <-
{
(Completion.create declared.name.txt ~env
~kind:
(Module
{docstring = declared.docstring; module_ = declared.item}))
with
deprecated = declared.deprecated;
docstring = declared.docstring;
}
:: localTables.resultRev)
| None ->
Log.log
(Printf.sprintf "Completion Module Not Found %s loc:%s\n" name
(Loc.toString loc))
let getItemsFromOpens ~opens ~localTables ~prefix ~exact ~completionContext =
opens
|> List.fold_left
(fun results env ->
let completionsFromThisOpen =
findAllCompletions ~env ~prefix ~exact
~namesUsed:localTables.LocalTables.namesUsed ~completionContext
in
completionsFromThisOpen @ results)
[]
let findLocalCompletionsForValuesAndConstructors ~(localTables : LocalTables.t)
~env ~prefix ~exact ~opens ~scope =
localTables |> LocalTables.populateValues ~env;
localTables |> LocalTables.populateConstructors ~env;
localTables |> LocalTables.populateModules ~env;
scope
|> Scope.iterValuesBeforeFirstOpen
(processLocalValue ~prefix ~exact ~env ~localTables);
scope
|> Scope.iterConstructorsBeforeFirstOpen
(processLocalConstructor ~prefix ~exact ~env ~localTables);
scope
|> Scope.iterModulesBeforeFirstOpen
(processLocalModule ~prefix ~exact ~env ~localTables);
let valuesFromOpens =
getItemsFromOpens ~opens ~localTables ~prefix ~exact
~completionContext:Value
in
scope
|> Scope.iterValuesAfterFirstOpen
(processLocalValue ~prefix ~exact ~env ~localTables);
scope
|> Scope.iterConstructorsAfterFirstOpen
(processLocalConstructor ~prefix ~exact ~env ~localTables);
scope
|> Scope.iterModulesAfterFirstOpen
(processLocalModule ~prefix ~exact ~env ~localTables);
List.rev_append localTables.resultRev valuesFromOpens
let findLocalCompletionsForValues ~(localTables : LocalTables.t) ~env ~prefix
~exact ~opens ~scope =
localTables |> LocalTables.populateValues ~env;
localTables |> LocalTables.populateModules ~env;
scope
|> Scope.iterValuesBeforeFirstOpen
(processLocalValue ~prefix ~exact ~env ~localTables);
scope
|> Scope.iterModulesBeforeFirstOpen
(processLocalModule ~prefix ~exact ~env ~localTables);
let valuesFromOpens =
getItemsFromOpens ~opens ~localTables ~prefix ~exact
~completionContext:Value
in
scope
|> Scope.iterValuesAfterFirstOpen
(processLocalValue ~prefix ~exact ~env ~localTables);
scope
|> Scope.iterModulesAfterFirstOpen
(processLocalModule ~prefix ~exact ~env ~localTables);
List.rev_append localTables.resultRev valuesFromOpens
let findLocalCompletionsForTypes ~(localTables : LocalTables.t) ~env ~prefix
~exact ~opens ~scope =
localTables |> LocalTables.populateTypes ~env;
localTables |> LocalTables.populateModules ~env;
scope
|> Scope.iterTypesBeforeFirstOpen
(processLocalType ~prefix ~exact ~env ~localTables);
scope
|> Scope.iterModulesBeforeFirstOpen
(processLocalModule ~prefix ~exact ~env ~localTables);
let valuesFromOpens =
getItemsFromOpens ~opens ~localTables ~prefix ~exact ~completionContext:Type
in
scope
|> Scope.iterTypesAfterFirstOpen
(processLocalType ~prefix ~exact ~env ~localTables);
scope
|> Scope.iterModulesAfterFirstOpen
(processLocalModule ~prefix ~exact ~env ~localTables);
List.rev_append localTables.resultRev valuesFromOpens
let findLocalCompletionsForModules ~(localTables : LocalTables.t) ~env ~prefix
~exact ~opens ~scope =
localTables |> LocalTables.populateModules ~env;
scope
|> Scope.iterModulesBeforeFirstOpen
(processLocalModule ~prefix ~exact ~env ~localTables);
let valuesFromOpens =
getItemsFromOpens ~opens ~localTables ~prefix ~exact
~completionContext:Module
in
scope
|> Scope.iterModulesAfterFirstOpen
(processLocalModule ~prefix ~exact ~env ~localTables);
List.rev_append localTables.resultRev valuesFromOpens
let findLocalCompletionsWithOpens ~pos ~(env : QueryEnv.t) ~prefix ~exact ~opens
~scope ~(completionContext : Completable.completionContext) =
(* TODO: handle arbitrary interleaving of opens and local bindings correctly *)
Log.log
("findLocalCompletionsWithOpens uri:" ^ Uri.toString env.file.uri ^ " pos:"
^ Pos.toString pos);
let localTables = LocalTables.create () in
match completionContext with
| Value | ValueOrField ->
findLocalCompletionsForValuesAndConstructors ~localTables ~env ~prefix
~exact ~opens ~scope
| Type ->
findLocalCompletionsForTypes ~localTables ~env ~prefix ~exact ~opens ~scope
| Module ->
findLocalCompletionsForModules ~localTables ~env ~prefix ~exact ~opens
~scope
| Field ->
(* There's no local completion for fields *)
[]
let getComplementaryCompletionsForTypedValue ~opens ~allFiles ~scope ~env prefix
=
let exact = false in
let localCompletionsWithOpens =
let localTables = LocalTables.create () in
findLocalCompletionsForValues ~localTables ~env ~prefix ~exact ~opens ~scope
in
let fileModules =
allFiles |> FileSet.elements
|> Utils.filterMap (fun name ->
if
Utils.checkName name ~prefix ~exact
&& not
(* TODO complete the namespaced name too *)
(Utils.fileNameHasUnallowedChars name)
then
Some
(Completion.create name ~synthetic:true ~env
~kind:(Completion.FileModule name))
else None)
in
localCompletionsWithOpens @ fileModules
let getCompletionsForPath ~debug ~opens ~full ~pos ~exact ~scope
~completionContext ~env path =
if debug then Printf.printf "Path %s\n" (path |> String.concat ".");
let allFiles = allFilesInPackage full.package in
match path with
| [] -> []
| [prefix] ->
let localCompletionsWithOpens =
findLocalCompletionsWithOpens ~pos ~env ~prefix ~exact ~opens ~scope
~completionContext
in
let fileModules =
allFiles |> FileSet.elements
|> Utils.filterMap (fun name ->
if
Utils.checkName name ~prefix ~exact
&& not
(* TODO complete the namespaced name too *)
(Utils.fileNameHasUnallowedChars name)
then
Some
(Completion.create name ~env ~kind:(Completion.FileModule name))
else None)
in
localCompletionsWithOpens @ fileModules
| moduleName :: path -> (
Log.log ("Path " ^ pathToString path);
match
getEnvWithOpens ~scope ~env ~package:full.package ~opens ~moduleName path
with
| Some (env, prefix) ->
Log.log "Got the env";
let namesUsed = Hashtbl.create 10 in
findAllCompletions ~env ~prefix ~exact ~namesUsed ~completionContext
| None -> [])
(** Completions intended for piping, from a completion path. *)
let completionsForPipeFromCompletionPath ~envCompletionIsMadeFrom ~opens ~pos
~scope ~debug ~prefix ~env ~rawOpens ~full completionPath =
let completionPathWithoutCurrentModule =
TypeUtils.removeCurrentModuleIfNeeded ~envCompletionIsMadeFrom
completionPath
in
let completionPathMinusOpens =
TypeUtils.removeOpensFromCompletionPath ~rawOpens ~package:full.package
completionPathWithoutCurrentModule
|> String.concat "."
in
let completionName name =
if completionPathMinusOpens = "" then name
else completionPathMinusOpens ^ "." ^ name
in
let completions =
completionPath @ [prefix]
|> getCompletionsForPath ~debug ~completionContext:Value ~exact:false ~opens
~full ~pos ~env ~scope
in
let completions =
completions
|> List.map (fun (completion : Completion.t) ->
{completion with name = completionName completion.name})
in
completions
let rec digToRecordFieldsForCompletion ~debug ~package ~opens ~full ~pos ~env
~scope path =
match
path
|> getCompletionsForPath ~debug ~completionContext:Type ~exact:true ~opens
~full ~pos ~env ~scope
with
| {kind = Type {kind = Abstract (Some (p, _))}} :: _ ->
(* This case happens when what we're looking for is a type alias.
This is the case in newer rescript-react versions where
ReactDOM.domProps is an alias for JsxEvent.t. *)
let pathRev = p |> Utils.expandPath in
pathRev |> List.rev
|> digToRecordFieldsForCompletion ~debug ~package ~opens ~full ~pos ~env
~scope
| {kind = Type {kind = Record fields}} :: _ -> Some fields
| _ -> None
let mkItem ?data ?additionalTextEdits name ~kind ~detail ~deprecated ~docstring
=
let docContent =
(match deprecated with
| None -> ""
| Some s -> "Deprecated: " ^ s ^ "\n\n")
^
match docstring with
| [] -> ""
| _ :: _ -> docstring |> String.concat "\n"
in
let tags =
match deprecated with
| None -> []
| Some _ -> [1 (* deprecated *)]
in
Protocol.
{
label = name;
kind;
tags;
detail;
documentation =
(if docContent = "" then None
else Some {kind = "markdown"; value = docContent});
sortText = None;
insertText = None;
insertTextFormat = None;
filterText = None;
data;
additionalTextEdits;
}
let completionToItem
{
Completion.name;
deprecated;
docstring;
kind;
sortText;
insertText;
insertTextFormat;
filterText;
detail;
env;
additionalTextEdits;
} ~full =
let item =
mkItem name ?additionalTextEdits
?data:(kindToData (full.file.uri |> Uri.toPath) kind)
~kind:(Completion.kindToInt kind)
~deprecated
~detail:
(match detail with
| None -> kindToDetail name kind
| Some detail -> detail)
~docstring:
(match
kindToDocumentation ~currentDocstring:docstring ~full ~env name kind
with
| "" -> []
| docstring -> [docstring])
in
{item with sortText; insertText; insertTextFormat; filterText}
let completionsGetTypeEnv = function
| {Completion.kind = Value typ; env} :: _ -> Some (typ, env)
| {Completion.kind = ObjLabel typ; env} :: _ -> Some (typ, env)
| {Completion.kind = Field ({typ}, _); env} :: _ -> Some (typ, env)
| _ -> None
type getCompletionsForContextPathMode = Regular | Pipe
let completionsGetCompletionType ~full completions =
let firstNonSyntheticCompletion =
List.find_opt (fun c -> not c.Completion.synthetic) completions
in
match firstNonSyntheticCompletion with
| Some {Completion.kind = Value typ; env}
| Some {Completion.kind = ObjLabel typ; env}
| Some {Completion.kind = Field ({typ}, _); env} ->
typ
|> TypeUtils.extractType ~env ~package:full.package
|> Option.map (fun (typ, _) -> (typ, env))
| Some {Completion.kind = Type typ; env} -> (
match TypeUtils.extractTypeFromResolvedType typ ~env ~full with
| None -> None
| Some extractedType -> Some (extractedType, env))
| Some {Completion.kind = ExtractedType (typ, _); env} -> Some (typ, env)
| _ -> None
let rec completionsGetCompletionType2 ~debug ~full ~opens ~rawOpens ~pos
completions =
let firstNonSyntheticCompletion =
List.find_opt (fun c -> not c.Completion.synthetic) completions
in
match firstNonSyntheticCompletion with
| Some
( {Completion.kind = Value typ; env}
| {Completion.kind = ObjLabel typ; env}
| {Completion.kind = Field ({typ}, _); env} ) ->
Some (TypeExpr typ, env)
| Some {Completion.kind = FollowContextPath (ctxPath, scope); env} ->
ctxPath
|> getCompletionsForContextPath ~debug ~full ~env ~exact:true ~opens
~rawOpens ~pos ~scope
|> completionsGetCompletionType2 ~debug ~full ~opens ~rawOpens ~pos
| Some {Completion.kind = Type typ; env} -> (
match TypeUtils.extractTypeFromResolvedType typ ~env ~full with
| None -> None
| Some extractedType -> Some (ExtractedType extractedType, env))
| Some {Completion.kind = ExtractedType (typ, _); env} ->
Some (ExtractedType typ, env)
| _ -> None
and completionsGetTypeEnv2 ~debug (completions : Completion.t list) ~full ~opens
~rawOpens ~pos =
let firstNonSyntheticCompletion =
List.find_opt (fun c -> not c.Completion.synthetic) completions
in
match firstNonSyntheticCompletion with
| Some {Completion.kind = Value typ; env} -> Some (typ, env)
| Some {Completion.kind = ObjLabel typ; env} -> Some (typ, env)
| Some {Completion.kind = Field ({typ}, _); env} -> Some (typ, env)
| Some {Completion.kind = FollowContextPath (ctxPath, scope); env} ->
ctxPath
|> getCompletionsForContextPath ~debug ~full ~opens ~rawOpens ~pos ~env
~exact:true ~scope
|> completionsGetTypeEnv2 ~debug ~full ~opens ~rawOpens ~pos
| _ -> None
and getCompletionsForContextPath ~debug ~full ~opens ~rawOpens ~pos ~env ~exact
~scope ?(mode = Regular) contextPath =
let envCompletionIsMadeFrom = env in
if debug then
Printf.printf "ContextPath %s\n"
(Completable.contextPathToString contextPath);
let package = full.package in
match contextPath with
| CPString ->
if Debug.verbose () then print_endline "[ctx_path]--> CPString";
[Completion.create "dummy" ~env ~kind:(Completion.Value Predef.type_string)]
| CPBool ->
if Debug.verbose () then print_endline "[ctx_path]--> CPBool";
[Completion.create "dummy" ~env ~kind:(Completion.Value Predef.type_bool)]
| CPInt ->
if Debug.verbose () then print_endline "[ctx_path]--> CPInt";
[Completion.create "dummy" ~env ~kind:(Completion.Value Predef.type_int)]
| CPFloat ->
if Debug.verbose () then print_endline "[ctx_path]--> CPFloat";
[Completion.create "dummy" ~env ~kind:(Completion.Value Predef.type_float)]
| CPArray None ->
if Debug.verbose () then print_endline "[ctx_path]--> CPArray (no payload)";
[
Completion.create "array" ~env
~kind:(Completion.Value (Ctype.newconstr Predef.path_array []));
]
| CPArray (Some cp) -> (
if Debug.verbose () then
print_endline "[ctx_path]--> CPArray (with payload)";
match mode with
| Regular -> (
match
cp
|> getCompletionsForContextPath ~debug ~full ~opens ~rawOpens ~pos ~env
~exact:true ~scope
|> completionsGetCompletionType ~full
with
| None -> []
| Some (typ, env) ->
[
Completion.create "dummy" ~env
~kind:
(Completion.ExtractedType (Tarray (env, ExtractedType typ), `Type));
])
| Pipe ->
(* Pipe completion with array just needs to know that it's an array, not
what inner type it has. *)
[
Completion.create "dummy" ~env
~kind:(Completion.Value (Ctype.newconstr Predef.path_array []));
])
| CPOption cp -> (
if Debug.verbose () then print_endline "[ctx_path]--> CPOption";
match
cp
|> getCompletionsForContextPath ~debug ~full ~opens ~rawOpens ~pos ~env
~exact:true ~scope
|> completionsGetCompletionType ~full
with
| None -> []
| Some (typ, env) ->
[
Completion.create "dummy" ~env
~kind:
(Completion.ExtractedType (Toption (env, ExtractedType typ), `Type));
])
| CPAwait cp -> (
if Debug.verbose () then print_endline "[ctx_path]--> CPAwait";
match
cp
|> getCompletionsForContextPath ~debug ~full ~opens ~rawOpens ~pos ~env
~exact:true ~scope
|> completionsGetCompletionType ~full
with
| Some (Tpromise (env, typ), _env) ->
[Completion.create "dummy" ~env ~kind:(Completion.Value typ)]
| _ -> [])
| CPId {path; completionContext; loc} ->
if Debug.verbose () then print_endline "[ctx_path]--> CPId";
(* Looks up the type of an identifier.
Because of reasons we sometimes don't get enough type
information when looking up identifiers where the type
has type parameters. This in turn means less completions.
There's a heuristic below that tries to look up the type
of the ID in the usual way first. But if the type found
still has uninstantiated type parameters, we check the
location for the identifier from the compiler type artifacts.
That type usually has the type params instantiated, if they are.
This leads to better completion.
However, we only do it in incremental type checking mode,
because more type information is always available in that mode. *)
let useTvarLookup = !Cfg.inIncrementalTypecheckingMode in
let byPath =
path
|> getCompletionsForPath ~debug ~opens ~full ~pos ~exact
~completionContext ~env ~scope
in
let hasTvars =
if useTvarLookup then
match byPath with
| [{kind = Value typ}] when TypeUtils.hasTvar typ -> true
| _ -> false
else false
in
let result =
if hasTvars then
let byLoc = TypeUtils.findTypeViaLoc loc ~full ~debug in
match (byLoc, byPath) with
| Some t, [({kind = Value _} as item)] -> [{item with kind = Value t}]
| _ -> byPath
else byPath
in
result
| CPApply (cp, labels) -> (
if Debug.verbose () then print_endline "[ctx_path]--> CPApply";
match
cp
|> getCompletionsForContextPath ~debug ~full ~opens ~rawOpens ~pos ~env
~exact:true ~scope
|> completionsGetCompletionType2 ~debug ~full ~opens ~rawOpens ~pos
with
| Some ((TypeExpr typ | ExtractedType (Tfunction {typ})), env) -> (
let rec reconstructFunctionType args tRet =
match args with
| [] -> tRet
| (label, tArg) :: rest ->
let restType = reconstructFunctionType rest tRet in
{typ with desc = Tarrow (label, tArg, restType, Cok, None)}
in
let rec processApply args labels =
match (args, labels) with
| _, [] -> args
| _, label :: (_ :: _ as nextLabels) ->
(* compute the application of the first label, then the next ones *)
let args = processApply args [label] in
processApply args nextLabels
| (Asttypes.Noloc.Nolabel, _) :: nextArgs, [Asttypes.Noloc.Nolabel] ->
nextArgs
| ((Labelled _, _) as arg) :: nextArgs, [Nolabel] ->
arg :: processApply nextArgs labels
| (Optional _, _) :: nextArgs, [Nolabel] -> processApply nextArgs labels
| ( (((Labelled s1 | Optional s1), _) as arg) :: nextArgs,
[(Labelled s2 | Optional s2)] ) ->
if s1 = s2 then nextArgs else arg :: processApply nextArgs labels
| ((Nolabel, _) as arg) :: nextArgs, [(Labelled _ | Optional _)] ->
arg :: processApply nextArgs labels
| [], [(Nolabel | Labelled _ | Optional _)] ->
(* should not happen, but just ignore extra arguments *) []
in
match TypeUtils.extractFunctionType ~env ~package ~digInto:false typ with
| args, tRet when args <> [] ->
let args = processApply args labels in
let retType = reconstructFunctionType args tRet in
[Completion.create "dummy" ~env ~kind:(Completion.Value retType)]
| _ -> [])
| _ -> [])
| CPField {contextPath = CPId {path; completionContext = Module}; fieldName}
->
if Debug.verbose () then print_endline "[ctx_path]--> CPField: M.field";
(* M.field *)
path @ [fieldName]
|> getCompletionsForPath ~debug ~opens ~full ~pos ~exact
~completionContext:Field ~env ~scope
| CPField {contextPath = cp; fieldName; posOfDot; exprLoc; inJsx} -> (
if Debug.verbose () then print_endline "[dot_completion]--> Triggered";
let completionsFromCtxPath =
cp
|> getCompletionsForContextPath ~debug ~full ~opens ~rawOpens ~pos ~env
~exact:true ~scope
in
let mainTypeCompletionEnv =
completionsFromCtxPath
|> completionsGetTypeEnv2 ~debug ~full ~opens ~rawOpens ~pos
in
match mainTypeCompletionEnv with
| None ->
if Debug.verbose () then
Printf.printf
"[dot_completion] Could not extract main type completion env.\n";
[]
| Some (typ, env) ->