-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathCompletionFrontEnd.ml
1554 lines (1536 loc) · 60.1 KB
/
CompletionFrontEnd.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 findArgCompletables ~(args : arg list) ~endPos ~posBeforeCursor
~(contextPath : Completable.contextPath) ~posAfterFunExpr
~firstCharBeforeCursorNoWhite ~charBeforeCursor ~isPipedExpr =
let fnHasCursor =
posAfterFunExpr <= posBeforeCursor && posBeforeCursor < endPos
in
let allNames =
List.fold_right
(fun arg allLabels ->
match arg with
| {label = Some labelled} -> labelled.name :: allLabels
| {label = None} -> allLabels)
args []
in
let unlabelledCount = ref (if isPipedExpr then 1 else 0) in
let someArgHadEmptyExprLoc = ref false in
let rec loop args =
match args with
| {label = Some labelled; exp} :: rest ->
if
labelled.posStart <= posBeforeCursor
&& posBeforeCursor < labelled.posEnd
then (
if Debug.verbose () then
print_endline "[findArgCompletables] Completing named arg #2";
Some (Completable.CnamedArg (contextPath, labelled.name, allNames)))
else if exp.pexp_loc |> Loc.hasPos ~pos:posBeforeCursor then (
if Debug.verbose () then
print_endline
"[findArgCompletables] Completing in the assignment of labelled \
argument";
match
CompletionExpressions.traverseExpr exp ~exprPath:[]
~pos:posBeforeCursor ~firstCharBeforeCursorNoWhite
with
| None -> None
| Some (prefix, nested) ->
if Debug.verbose () then
print_endline
"[findArgCompletables] Completing for labelled argument value";
Some
(Cexpression
{
contextPath =
CArgument
{
functionContextPath = contextPath;
argumentLabel = Labelled labelled.name;
};
prefix;
nested = List.rev nested;
}))
else if CompletionExpressions.isExprHole exp then (
if Debug.verbose () then
print_endline "[findArgCompletables] found exprhole";
Some
(Cexpression
{
contextPath =
CArgument
{
functionContextPath = contextPath;
argumentLabel = Labelled labelled.name;
};
prefix = "";
nested = [];
}))
else loop rest
| {label = None; exp} :: rest ->
if Debug.verbose () then
Printf.printf "[findArgCompletable] unlabelled arg expr is: %s \n"
(DumpAst.printExprItem ~pos:posBeforeCursor ~indentation:0 exp);
(* Track whether there was an arg with an empty loc (indicates parser error)*)
if CursorPosition.locIsEmpty exp.pexp_loc ~pos:posBeforeCursor then
someArgHadEmptyExprLoc := true;
if Res_parsetree_viewer.is_template_literal exp then None
else if exp.pexp_loc |> Loc.hasPos ~pos:posBeforeCursor then (
if Debug.verbose () then
print_endline
"[findArgCompletables] Completing in an unlabelled argument";
match
CompletionExpressions.traverseExpr exp ~pos:posBeforeCursor
~firstCharBeforeCursorNoWhite ~exprPath:[]
with
| None ->
if Debug.verbose () then
print_endline
"[findArgCompletables] found nothing when traversing expr";
None
| Some (prefix, nested) ->
if Debug.verbose () then
print_endline
"[findArgCompletables] completing for unlabelled argument #2";
Some
(Cexpression
{
contextPath =
CArgument
{
functionContextPath = contextPath;
argumentLabel =
Unlabelled {argumentPosition = !unlabelledCount};
};
prefix;
nested = List.rev nested;
}))
else if CompletionExpressions.isExprHole exp then (
if Debug.verbose () then
print_endline "[findArgCompletables] found an exprhole #2";
Some
(Cexpression
{
contextPath =
CArgument
{
functionContextPath = contextPath;
argumentLabel =
Unlabelled {argumentPosition = !unlabelledCount};
};
prefix = "";
nested = [];
}))
else (
unlabelledCount := !unlabelledCount + 1;
loop rest)
| [] ->
let hadEmptyExpLoc = !someArgHadEmptyExprLoc in
if fnHasCursor then (
if Debug.verbose () then
print_endline "[findArgCompletables] Function has cursor";
match charBeforeCursor with
| Some '~' ->
if Debug.verbose () then
print_endline "[findArgCompletables] '~' is before cursor";
Some (Completable.CnamedArg (contextPath, "", allNames))
| _ when hadEmptyExpLoc ->
(* Special case: `Console.log(arr->)`, completing on the pipe.
This match branch happens when the fn call has the cursor and:
- there's no argument label or expr that has the cursor
- there's an argument expression with an empty loc (indicates parser error)
In that case, it's safer to not complete for the unlabelled function
argument (which we do otherwise), and instead not complete and let the
completion engine move into the arguments one by one instead to check
for completions.
This can be handled in a more robust way in a future refactor of the
completion engine logic. *)
if Debug.verbose () then
print_endline
"[findArgCompletables] skipping completion in fn call because \
arg had empty loc";
None
| _
when firstCharBeforeCursorNoWhite = Some '('
|| firstCharBeforeCursorNoWhite = Some ',' ->
(* Checks to ensure that completing for empty unlabelled arg makes
sense by checking what's left of the cursor. *)
if Debug.verbose () then
Printf.printf
"[findArgCompletables] Completing for unlabelled argument value \
because nothing matched and is not labelled argument name \
completion. isPipedExpr: %b\n"
isPipedExpr;
Some
(Cexpression
{
contextPath =
CArgument
{
functionContextPath = contextPath;
argumentLabel =
Unlabelled {argumentPosition = !unlabelledCount};
};
prefix = "";
nested = [];
})
| _ -> None)
else None
in
match args with
(* Special handling for empty fn calls, e.g. `let _ = someFn(<com>)` *)
| [
{label = None; exp = {pexp_desc = Pexp_construct ({txt = Lident "()"}, _)}};
]
when fnHasCursor ->
if Debug.verbose () then
print_endline "[findArgCompletables] Completing for unit argument";
Some
(Completable.Cexpression
{
contextPath =
CArgument
{
functionContextPath = contextPath;
argumentLabel =
Unlabelled
{argumentPosition = (if isPipedExpr then 1 else 0)};
};
prefix = "";
nested = [];
})
| _ -> loop args
let rec exprToContextPathInner (e : Parsetree.expression) =
match e.pexp_desc with
| Pexp_constant (Pconst_string _) -> Some Completable.CPString
| Pexp_constant (Pconst_integer _) -> Some CPInt
| Pexp_constant (Pconst_float _) -> Some CPFloat
| Pexp_construct ({txt = Lident ("true" | "false")}, None) -> Some CPBool
| Pexp_array exprs ->
Some
(CPArray
(match exprs with
| [] -> None
| exp :: _ -> exprToContextPath exp))
| Pexp_ident {txt = Lident ("|." | "|.u")} -> None
| Pexp_ident {txt; loc} ->
Some
(CPId {path = Utils.flattenLongIdent txt; completionContext = Value; loc})
| Pexp_field (e1, {txt = Lident name}) -> (
match exprToContextPath e1 with
| Some contextPath -> Some (CPField (contextPath, name))
| _ -> None)
| Pexp_field (_, {loc; txt = Ldot (lid, name)}) ->
(* Case x.M.field ignore the x part *)
Some
(CPField
( CPId
{
path = Utils.flattenLongIdent lid;
completionContext = Module;
loc;
},
name ))
| Pexp_send (e1, {txt}) -> (
match exprToContextPath e1 with
| None -> None
| Some contexPath -> Some (CPObj (contexPath, txt)))
| Pexp_apply
( {pexp_desc = Pexp_ident {txt = Lident ("|." | "|.u")}},
[
(_, lhs);
(_, {pexp_desc = Pexp_apply (d, args); pexp_loc; pexp_attributes});
] ) ->
(* Transform away pipe with apply call *)
exprToContextPath
{
pexp_desc = Pexp_apply (d, (Nolabel, lhs) :: args);
pexp_loc;
pexp_attributes;
}
| Pexp_apply
( {pexp_desc = Pexp_ident {txt = Lident ("|." | "|.u")}},
[(_, lhs); (_, {pexp_desc = Pexp_ident id; pexp_loc; pexp_attributes})]
) ->
(* Transform away pipe with identifier *)
exprToContextPath
{
pexp_desc =
Pexp_apply
( {pexp_desc = Pexp_ident id; pexp_loc; pexp_attributes},
[(Nolabel, lhs)] );
pexp_loc;
pexp_attributes;
}
| Pexp_apply (e1, args) -> (
match exprToContextPath e1 with
| None -> None
| Some contexPath -> Some (CPApply (contexPath, args |> List.map fst)))
| Pexp_tuple exprs ->
let exprsAsContextPaths = exprs |> List.filter_map exprToContextPath in
if List.length exprs = List.length exprsAsContextPaths then
Some (CTuple exprsAsContextPaths)
else None
| _ -> None
and exprToContextPath (e : Parsetree.expression) =
match
( Res_parsetree_viewer.has_await_attribute e.pexp_attributes,
exprToContextPathInner e )
with
| true, Some ctxPath -> Some (CPAwait ctxPath)
| false, Some ctxPath -> Some ctxPath
| _, None -> None
let completePipeChain (exp : Parsetree.expression) =
(* Complete the end of pipe chains by reconstructing the pipe chain as a single pipe,
so it can be completed.
Example:
someArray->Js.Array2.filter(v => v > 10)->Js.Array2.map(v => v + 2)->
will complete as:
Js.Array2.map(someArray->Js.Array2.filter(v => v > 10), v => v + 2)->
*)
match exp.pexp_desc with
(* When the left side of the pipe we're completing is a function application.
Example: someArray->Js.Array2.map(v => v + 2)-> *)
| Pexp_apply
( {pexp_desc = Pexp_ident {txt = Lident ("|." | "|.u")}},
[_; (_, {pexp_desc = Pexp_apply (d, _)})] ) ->
exprToContextPath exp |> Option.map (fun ctxPath -> (ctxPath, d.pexp_loc))
(* When the left side of the pipe we're completing is an identifier application.
Example: someArray->filterAllTheGoodStuff-> *)
| Pexp_apply
( {pexp_desc = Pexp_ident {txt = Lident ("|." | "|.u")}},
[_; (_, {pexp_desc = Pexp_ident _; pexp_loc})] ) ->
exprToContextPath exp |> Option.map (fun ctxPath -> (ctxPath, pexp_loc))
| _ -> None
let completionWithParser1 ~currentFile ~debug ~offset ~path ~posCursor
?findThisExprLoc text =
let offsetNoWhite = Utils.skipWhite text (offset - 1) in
let posNoWhite =
let line, col = posCursor in
(line, max 0 col - offset + offsetNoWhite)
in
(* Identifies the first character before the cursor that's not white space.
Should be used very sparingly, but can be used to drive completion triggering
in scenarios where the parser eats things we'd need to complete.
Example: let {whatever, <cursor>}, char is ','. *)
let firstCharBeforeCursorNoWhite =
if offsetNoWhite < String.length text && offsetNoWhite >= 0 then
Some text.[offsetNoWhite]
else None
in
let charAtCursor =
if offset < String.length text then text.[offset] else '\n'
in
let posBeforeCursor = Pos.posBeforeCursor posCursor in
let charBeforeCursor, blankAfterCursor =
match Pos.positionToOffset text posCursor with
| Some offset when offset > 0 -> (
let charBeforeCursor = text.[offset - 1] in
match charAtCursor with
| ' ' | '\t' | '\r' | '\n' ->
(Some charBeforeCursor, Some charBeforeCursor)
| _ -> (Some charBeforeCursor, None))
| _ -> (None, None)
in
let flattenLidCheckDot ?(jsx = true) (lid : Longident.t Location.loc) =
(* Flatten an identifier keeping track of whether the current cursor
is after a "." in the id followed by a blank character.
In that case, cut the path after ".". *)
let cutAtOffset =
let idStart = Loc.start lid.loc in
match blankAfterCursor with
| Some '.' ->
if fst posBeforeCursor = fst idStart then
Some (snd posBeforeCursor - snd idStart)
else None
| _ -> None
in
Utils.flattenLongIdent ~cutAtOffset ~jsx lid.txt
in
let currentCtxPath = ref None in
let processingFun = ref None in
let setCurrentCtxPath ctxPath =
if !Cfg.debugFollowCtxPath then
Printf.printf "setting current ctxPath: %s\n"
(Completable.contextPathToString ctxPath);
currentCtxPath := Some ctxPath
in
let resetCurrentCtxPath ctxPath =
(match (!currentCtxPath, ctxPath) with
| None, None -> ()
| _ ->
if !Cfg.debugFollowCtxPath then
Printf.printf "resetting current ctxPath to: %s\n"
(match ctxPath with
| None -> "None"
| Some ctxPath -> Completable.contextPathToString ctxPath));
currentCtxPath := ctxPath
in
let found = ref false in
let result = ref None in
let scope = ref (Scope.create ()) in
let setResultOpt x =
if !result = None then
match x with
| None ->
if Debug.verbose () then
print_endline
"[set_result] did not set new result because result already was set";
()
| Some x ->
if Debug.verbose () then
Printf.printf "[set_result] set new result to %s\n"
(Completable.toString x);
result := Some (x, !scope)
in
let setResult x = setResultOpt (Some x) in
let scopeValueDescription (vd : Parsetree.value_description) =
scope :=
!scope |> Scope.addValue ~name:vd.pval_name.txt ~loc:vd.pval_name.loc
in
let rec scopePattern ?contextPath
?(patternPath : Completable.nestedPath list = [])
(pat : Parsetree.pattern) =
let contextPathToSave =
match (contextPath, patternPath) with
| maybeContextPath, [] -> maybeContextPath
| Some contextPath, patternPath ->
Some
(Completable.CPatternPath
{rootCtxPath = contextPath; nested = List.rev patternPath})
| _ -> None
in
match pat.ppat_desc with
| Ppat_any -> ()
| Ppat_var {txt; loc} ->
scope :=
!scope |> Scope.addValue ~name:txt ~loc ?contextPath:contextPathToSave
| Ppat_alias (p, asA) ->
scopePattern p ~patternPath ?contextPath;
let ctxPath =
if contextPathToSave = None then
match p with
| {ppat_desc = Ppat_var {txt; loc}} ->
Some
(Completable.CPId {path = [txt]; completionContext = Value; loc})
| _ -> None
else None
in
scope :=
!scope |> Scope.addValue ~name:asA.txt ~loc:asA.loc ?contextPath:ctxPath
| Ppat_constant _ | Ppat_interval _ -> ()
| Ppat_tuple pl ->
pl
|> List.iteri (fun index p ->
scopePattern p
~patternPath:(NTupleItem {itemNum = index} :: patternPath)
?contextPath)
| Ppat_construct (_, None) -> ()
| Ppat_construct ({txt}, Some {ppat_desc = Ppat_tuple pl}) ->
pl
|> List.iteri (fun index p ->
scopePattern p
~patternPath:
(NVariantPayload
{
itemNum = index;
constructorName = Utils.getUnqualifiedName txt;
}
:: patternPath)
?contextPath)
| Ppat_construct ({txt}, Some p) ->
scopePattern
~patternPath:
(NVariantPayload
{itemNum = 0; constructorName = Utils.getUnqualifiedName txt}
:: patternPath)
?contextPath p
| Ppat_variant (_, None) -> ()
| Ppat_variant (txt, Some {ppat_desc = Ppat_tuple pl}) ->
pl
|> List.iteri (fun index p ->
scopePattern p
~patternPath:
(NPolyvariantPayload {itemNum = index; constructorName = txt}
:: patternPath)
?contextPath)
| Ppat_variant (txt, Some p) ->
scopePattern
~patternPath:
(NPolyvariantPayload {itemNum = 0; constructorName = txt}
:: patternPath)
?contextPath p
| Ppat_record (fields, _) ->
fields
|> List.iter (fun (fname, p) ->
match fname with
| {Location.txt = Longident.Lident fname} ->
scopePattern
~patternPath:
(Completable.NFollowRecordField {fieldName = fname}
:: patternPath)
?contextPath p
| _ -> ())
| Ppat_array pl ->
pl
|> List.iter
(scopePattern ~patternPath:(NArray :: patternPath) ?contextPath)
| Ppat_or (p1, _) -> scopePattern ~patternPath ?contextPath p1
| Ppat_constraint (p, coreType) ->
scopePattern ~patternPath
?contextPath:(TypeUtils.contextPathFromCoreType coreType)
p
| Ppat_type _ -> ()
| Ppat_lazy p -> scopePattern ~patternPath ?contextPath p
| Ppat_unpack {txt; loc} ->
scope :=
!scope |> Scope.addValue ~name:txt ~loc ?contextPath:contextPathToSave
| Ppat_exception p -> scopePattern ~patternPath ?contextPath p
| Ppat_extension _ -> ()
| Ppat_open (_, p) -> scopePattern ~patternPath ?contextPath p
in
let locHasCursor = CursorPosition.locHasCursor ~pos:posBeforeCursor in
let locIsEmpty = CursorPosition.locIsEmpty ~pos:posBeforeCursor in
let completePattern ?contextPath (pat : Parsetree.pattern) =
match
( pat
|> CompletionPatterns.traversePattern ~patternPath:[] ~locHasCursor
~firstCharBeforeCursorNoWhite ~posBeforeCursor,
contextPath )
with
| Some (prefix, nestedPattern), Some ctxPath ->
if Debug.verbose () then
Printf.printf "[completePattern] found pattern that can be completed\n";
setResult
(Completable.Cpattern
{
contextPath = ctxPath;
prefix;
nested = List.rev nestedPattern;
fallback = None;
patternMode = Default;
})
| _ -> ()
in
let scopeValueBinding (vb : Parsetree.value_binding) =
let contextPath =
(* Pipe chains get special treatment here, because when assigning values
we want the return of the entire pipe chain as a function call, rather
than as a pipe completion call. *)
match completePipeChain vb.pvb_expr with
| Some (ctxPath, _) -> Some ctxPath
| None -> exprToContextPath vb.pvb_expr
in
scopePattern ?contextPath vb.pvb_pat
in
let scopeTypeKind (tk : Parsetree.type_kind) =
match tk with
| Ptype_variant constrDecls ->
constrDecls
|> List.iter (fun (cd : Parsetree.constructor_declaration) ->
scope :=
!scope
|> Scope.addConstructor ~name:cd.pcd_name.txt ~loc:cd.pcd_loc)
| Ptype_record labelDecls ->
labelDecls
|> List.iter (fun (ld : Parsetree.label_declaration) ->
scope :=
!scope |> Scope.addField ~name:ld.pld_name.txt ~loc:ld.pld_loc)
| _ -> ()
in
let scopeTypeDeclaration (td : Parsetree.type_declaration) =
scope :=
!scope |> Scope.addType ~name:td.ptype_name.txt ~loc:td.ptype_name.loc;
scopeTypeKind td.ptype_kind
in
let scopeModuleBinding (mb : Parsetree.module_binding) =
scope :=
!scope |> Scope.addModule ~name:mb.pmb_name.txt ~loc:mb.pmb_name.loc
in
let scopeModuleDeclaration (md : Parsetree.module_declaration) =
scope :=
!scope |> Scope.addModule ~name:md.pmd_name.txt ~loc:md.pmd_name.loc
in
let inJsxContext = ref false in
(* Identifies expressions where we can do typed pattern or expr completion. *)
let typedCompletionExpr (exp : Parsetree.expression) =
let debugTypedCompletionExpr = false in
if exp.pexp_loc |> CursorPosition.locHasCursor ~pos:posBeforeCursor then (
if Debug.verbose () && debugTypedCompletionExpr then
print_endline "[typedCompletionExpr] Has cursor";
match exp.pexp_desc with
(* No cases means there's no `|` yet in the switch *)
| Pexp_match (({pexp_desc = Pexp_ident _} as expr), []) ->
if Debug.verbose () && debugTypedCompletionExpr then
print_endline "[typedCompletionExpr] No cases, with ident";
if locHasCursor expr.pexp_loc then (
if Debug.verbose () && debugTypedCompletionExpr then
print_endline "[typedCompletionExpr] No cases - has cursor";
(* We can do exhaustive switch completion if this is an ident we can
complete from. *)
match exprToContextPath expr with
| None -> ()
| Some contextPath ->
setResult (CexhaustiveSwitch {contextPath; exprLoc = exp.pexp_loc}))
| Pexp_match (_expr, []) ->
(* switch x { } *)
if Debug.verbose () && debugTypedCompletionExpr then
print_endline "[typedCompletionExpr] No cases, rest";
()
| Pexp_match (expr, [{pc_lhs; pc_rhs}])
when locHasCursor expr.pexp_loc
&& CompletionExpressions.isExprHole pc_rhs
&& CompletionPatterns.isPatternHole pc_lhs ->
(* switch x { | } when we're in the switch expr itself. *)
if Debug.verbose () && debugTypedCompletionExpr then
print_endline
"[typedCompletionExpr] No cases (expr and pat holes), rest";
()
| Pexp_match
( exp,
[
{
pc_lhs =
{
ppat_desc =
Ppat_extension ({txt = "rescript.patternhole"}, _);
};
};
] ) -> (
(* A single case that's a pattern hole typically means `switch x { | }`. Complete as the pattern itself with nothing nested. *)
match exprToContextPath exp with
| None -> ()
| Some ctxPath ->
setResult
(Completable.Cpattern
{
contextPath = ctxPath;
nested = [];
prefix = "";
fallback = None;
patternMode = Default;
}))
| Pexp_match (exp, cases) -> (
if Debug.verbose () && debugTypedCompletionExpr then
print_endline "[typedCompletionExpr] Has cases";
(* If there's more than one case, or the case isn't a pattern hole, figure out if we're completing another
broken parser case (`switch x { | true => () | <com> }` for example). *)
match exp |> exprToContextPath with
| None ->
if Debug.verbose () && debugTypedCompletionExpr then
print_endline "[typedCompletionExpr] Has cases - no ctx path"
| Some ctxPath -> (
if Debug.verbose () && debugTypedCompletionExpr then
print_endline "[typedCompletionExpr] Has cases - has ctx path";
let hasCaseWithCursor =
cases
|> List.find_opt (fun case ->
locHasCursor case.Parsetree.pc_lhs.ppat_loc)
|> Option.is_some
in
let hasCaseWithEmptyLoc =
cases
|> List.find_opt (fun case ->
locIsEmpty case.Parsetree.pc_lhs.ppat_loc)
|> Option.is_some
in
if Debug.verbose () && debugTypedCompletionExpr then
Printf.printf
"[typedCompletionExpr] Has cases - has ctx path - \
hasCaseWithEmptyLoc: %b, hasCaseWithCursor: %b\n"
hasCaseWithEmptyLoc hasCaseWithCursor;
match (hasCaseWithEmptyLoc, hasCaseWithCursor) with
| _, true ->
(* Always continue if there's a case with the cursor *)
()
| true, false ->
(* If there's no case with the cursor, but a broken parser case, complete for the top level. *)
setResult
(Completable.Cpattern
{
contextPath = ctxPath;
nested = [];
prefix = "";
fallback = None;
patternMode = Default;
})
| false, false -> ()))
| _ -> ())
in
let structure (iterator : Ast_iterator.iterator)
(structure : Parsetree.structure) =
let oldScope = !scope in
Ast_iterator.default_iterator.structure iterator structure;
scope := oldScope
in
let structure_item (iterator : Ast_iterator.iterator)
(item : Parsetree.structure_item) =
let processed = ref false in
(match item.pstr_desc with
| Pstr_open {popen_lid} ->
scope := !scope |> Scope.addOpen ~lid:popen_lid.txt
| Pstr_primitive vd -> scopeValueDescription vd
| Pstr_value (recFlag, bindings) ->
if recFlag = Recursive then bindings |> List.iter scopeValueBinding;
bindings |> List.iter (fun vb -> iterator.value_binding iterator vb);
if recFlag = Nonrecursive then bindings |> List.iter scopeValueBinding;
processed := true
| Pstr_type (recFlag, decls) ->
if recFlag = Recursive then decls |> List.iter scopeTypeDeclaration;
decls |> List.iter (fun td -> iterator.type_declaration iterator td);
if recFlag = Nonrecursive then decls |> List.iter scopeTypeDeclaration;
processed := true
| Pstr_module mb ->
iterator.module_binding iterator mb;
scopeModuleBinding mb;
processed := true
| Pstr_recmodule mbs ->
mbs |> List.iter scopeModuleBinding;
mbs |> List.iter (fun b -> iterator.module_binding iterator b);
processed := true
| _ -> ());
if not !processed then
Ast_iterator.default_iterator.structure_item iterator item
in
let value_binding (iterator : Ast_iterator.iterator)
(value_binding : Parsetree.value_binding) =
let oldInJsxContext = !inJsxContext in
if Utils.isJsxComponent value_binding then inJsxContext := true;
(match value_binding with
| {pvb_pat = {ppat_desc = Ppat_constraint (_pat, coreType)}; pvb_expr}
when locHasCursor pvb_expr.pexp_loc -> (
(* Expression with derivable type annotation.
E.g: let x: someRecord = {<com>} *)
match
( TypeUtils.contextPathFromCoreType coreType,
pvb_expr
|> CompletionExpressions.traverseExpr ~exprPath:[]
~pos:posBeforeCursor ~firstCharBeforeCursorNoWhite )
with
| Some ctxPath, Some (prefix, nested) ->
setResult
(Completable.Cexpression
{contextPath = ctxPath; prefix; nested = List.rev nested})
| _ -> ())
| {pvb_pat = {ppat_desc = Ppat_var {loc}}; pvb_expr}
when locHasCursor pvb_expr.pexp_loc -> (
(* Expression without a type annotation. We can complete this if this
has compiled previously and there's a type available for the identifier itself.
This is nice because the type is assigned even if the assignment isn't complete.
E.g: let x = {name: "name", <com>}, when `x` has compiled. *)
match
pvb_expr
|> CompletionExpressions.traverseExpr ~exprPath:[] ~pos:posBeforeCursor
~firstCharBeforeCursorNoWhite
with
| Some (prefix, nested) ->
(* This completion should be low prio, so let any deeper completion
hit first, and only set this TypeAtPos completion if nothing else
here hit. *)
Ast_iterator.default_iterator.value_binding iterator value_binding;
setResult
(Completable.Cexpression
{contextPath = CTypeAtPos loc; prefix; nested = List.rev nested})
| _ -> ())
| {
pvb_pat = {ppat_desc = Ppat_constraint (_pat, coreType); ppat_loc};
pvb_expr;
}
when locHasCursor value_binding.pvb_loc
&& locHasCursor ppat_loc = false
&& locHasCursor pvb_expr.pexp_loc = false
&& CompletionExpressions.isExprHole pvb_expr -> (
(* Expression with derivable type annotation, when the expression is empty (expr hole).
E.g: let x: someRecord = <com> *)
match TypeUtils.contextPathFromCoreType coreType with
| Some ctxPath ->
setResult
(Completable.Cexpression
{contextPath = ctxPath; prefix = ""; nested = []})
| _ -> ())
| {pvb_pat; pvb_expr} when locHasCursor pvb_pat.ppat_loc -> (
(* Completing a destructuring.
E.g: let {<com>} = someVar *)
match
( pvb_pat
|> CompletionPatterns.traversePattern ~patternPath:[] ~locHasCursor
~firstCharBeforeCursorNoWhite ~posBeforeCursor,
exprToContextPath pvb_expr )
with
| Some (prefix, nested), Some ctxPath ->
setResult
(Completable.Cpattern
{
contextPath = ctxPath;
prefix;
nested = List.rev nested;
fallback = None;
patternMode = Destructuring;
})
| _ -> ())
| _ -> ());
Ast_iterator.default_iterator.value_binding iterator value_binding;
inJsxContext := oldInJsxContext
in
let signature (iterator : Ast_iterator.iterator)
(signature : Parsetree.signature) =
let oldScope = !scope in
Ast_iterator.default_iterator.signature iterator signature;
scope := oldScope
in
let signature_item (iterator : Ast_iterator.iterator)
(item : Parsetree.signature_item) =
let processed = ref false in
(match item.psig_desc with
| Psig_open {popen_lid} ->
scope := !scope |> Scope.addOpen ~lid:popen_lid.txt
| Psig_value vd -> scopeValueDescription vd
| Psig_type (recFlag, decls) ->
if recFlag = Recursive then decls |> List.iter scopeTypeDeclaration;
decls |> List.iter (fun td -> iterator.type_declaration iterator td);
if recFlag = Nonrecursive then decls |> List.iter scopeTypeDeclaration;
processed := true
| Psig_module md ->
iterator.module_declaration iterator md;
scopeModuleDeclaration md;
processed := true
| Psig_recmodule mds ->
mds |> List.iter scopeModuleDeclaration;
mds |> List.iter (fun d -> iterator.module_declaration iterator d);
processed := true
| _ -> ());
if not !processed then
Ast_iterator.default_iterator.signature_item iterator item
in
let attribute (iterator : Ast_iterator.iterator)
((id, payload) : Parsetree.attribute) =
(if String.length id.txt >= 4 && String.sub id.txt 0 4 = "res." then
(* skip: internal parser attribute *) ()
else if id.loc.loc_ghost then ()
else if id.loc |> Loc.hasPos ~pos:posBeforeCursor then
let posStart, posEnd = Loc.range id.loc in
match
(Pos.positionToOffset text posStart, Pos.positionToOffset text posEnd)
with
| Some offsetStart, Some offsetEnd ->
(* Can't trust the parser's location
E.g. @foo. let x... gives as label @foo.let *)
let label =
let rawLabel =
String.sub text offsetStart (offsetEnd - offsetStart)
in
let ( ++ ) x y =
match (x, y) with
| Some i1, Some i2 -> Some (min i1 i2)
| Some _, None -> x
| None, _ -> y
in
let label =
match
String.index_opt rawLabel ' '
++ String.index_opt rawLabel '\t'
++ String.index_opt rawLabel '\r'
++ String.index_opt rawLabel '\n'
with
| None -> rawLabel
| Some i -> String.sub rawLabel 0 i
in
if label <> "" && label.[0] = '@' then
String.sub label 1 (String.length label - 1)
else label
in
found := true;
if debug then
Printf.printf "Attribute id:%s:%s label:%s\n" id.txt
(Loc.toString id.loc) label;
setResult (Completable.Cdecorator label)
| _ -> ()
else if id.txt = "module" then
match payload with
| PStr
[
{
pstr_desc =
Pstr_eval
( {pexp_loc; pexp_desc = Pexp_constant (Pconst_string (s, _))},
_ );
};
]
when locHasCursor pexp_loc ->
if Debug.verbose () then
print_endline "[decoratorCompletion] Found @module";
setResult (Completable.CdecoratorPayload (Module s))
| PStr
[
{
pstr_desc =
Pstr_eval
( {
pexp_desc =
Pexp_record (({txt = Lident "from"}, fromExpr) :: _, _);
},
_ );
};
]
when locHasCursor fromExpr.pexp_loc
|| locIsEmpty fromExpr.pexp_loc
&& CompletionExpressions.isExprHole fromExpr -> (
if Debug.verbose () then
print_endline
"[decoratorCompletion] Found @module with import attributes and \
cursor on \"from\"";
match
( locHasCursor fromExpr.pexp_loc,
locIsEmpty fromExpr.pexp_loc,
CompletionExpressions.isExprHole fromExpr,
fromExpr )
with
| true, _, _, {pexp_desc = Pexp_constant (Pconst_string (s, _))} ->
if Debug.verbose () then
print_endline
"[decoratorCompletion] @module `from` payload was string";
setResult (Completable.CdecoratorPayload (Module s))
| false, true, true, _ ->
if Debug.verbose () then
print_endline
"[decoratorCompletion] @module `from` payload was expr hole";
setResult (Completable.CdecoratorPayload (Module ""))
| _ -> ())
| PStr [{pstr_desc = Pstr_eval (expr, _)}] -> (
if Debug.verbose () then
print_endline
"[decoratorCompletion] Found @module with non-string payload";
match
CompletionExpressions.traverseExpr expr ~exprPath:[]
~pos:posBeforeCursor ~firstCharBeforeCursorNoWhite
with
| None -> ()
| Some (prefix, nested) ->
if Debug.verbose () then
print_endline "[decoratorCompletion] Found @module record path";
setResult
(Completable.CdecoratorPayload
(ModuleWithImportAttributes {nested = List.rev nested; prefix}))
)
| _ -> ()
else if id.txt = "jsxConfig" then
match payload with
| PStr [{pstr_desc = Pstr_eval (expr, _)}] -> (
if Debug.verbose () then
print_endline "[decoratorCompletion] Found @jsxConfig";
match
CompletionExpressions.traverseExpr expr ~exprPath:[]
~pos:posBeforeCursor ~firstCharBeforeCursorNoWhite
with
| None -> ()
| Some (prefix, nested) ->
if Debug.verbose () then
print_endline "[decoratorCompletion] Found @jsxConfig path!";
setResult
(Completable.CdecoratorPayload
(JsxConfig {nested = List.rev nested; prefix})))
| _ -> ());
Ast_iterator.default_iterator.attribute iterator (id, payload)
in
let rec iterateFnArguments ~args ~iterator ~isPipe
(argCompletable : Completable.t option) =
match argCompletable with
| None -> (
match !currentCtxPath with
| None -> ()
| Some functionContextPath ->
let currentUnlabelledCount = ref (if isPipe then 1 else 0) in
args
|> List.iter (fun (arg : arg) ->
let previousCtxPath = !currentCtxPath in
setCurrentCtxPath
(CArgument
{
functionContextPath;
argumentLabel =
(match arg with
| {label = None} ->
let current = !currentUnlabelledCount in
currentUnlabelledCount := current + 1;
Unlabelled {argumentPosition = current}
| {label = Some {name; opt = true}} -> Optional name
| {label = Some {name; opt = false}} -> Labelled name);
});
expr iterator arg.exp;
resetCurrentCtxPath previousCtxPath))
| Some argCompletable -> setResult argCompletable
and iterateJsxProps ~iterator (props : CompletionJsx.jsxProps) =
props.props
|> List.iter (fun (prop : CompletionJsx.prop) ->
let previousCtxPath = !currentCtxPath in
setCurrentCtxPath
(CJsxPropValue
{
pathToComponent =
Utils.flattenLongIdent ~jsx:true props.compName.txt;
propName = prop.name;
emptyJsxPropNameHint = None;
});
expr iterator prop.exp;
resetCurrentCtxPath previousCtxPath)
and expr (iterator : Ast_iterator.iterator) (expr : Parsetree.expression) =
let oldInJsxContext = !inJsxContext in
let processed = ref false in
let setFound () =
found := true;
if debug then
Printf.printf "posCursor:[%s] posNoWhite:[%s] Found expr:%s\n"
(Pos.toString posCursor) (Pos.toString posNoWhite)
(Loc.toString expr.pexp_loc)
in
(match findThisExprLoc with
| Some loc when expr.pexp_loc = loc -> (
match exprToContextPath expr with