-
Notifications
You must be signed in to change notification settings - Fork 485
Expand file tree
/
Copy pathcompletion_front_end.ml
More file actions
1909 lines (1890 loc) · 72.9 KB
/
Copy pathcompletion_front_end.ml
File metadata and controls
1909 lines (1890 loc) · 72.9 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
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 Shared_types
let find_arg_completables ~(args : arg list) ~end_pos ~pos_before_cursor
~(context_path : Completable.context_path) ~pos_after_fun_expr
~first_char_before_cursor_no_white ~char_before_cursor ~is_piped_expr =
let fn_has_cursor =
pos_after_fun_expr <= pos_before_cursor && pos_before_cursor < end_pos
in
let all_names =
List.fold_right
(fun arg all_labels ->
match arg with
| {label = Some labelled} -> labelled.name :: all_labels
| {label = None} -> all_labels)
args []
in
let unlabelled_count = ref (if is_piped_expr then 1 else 0) in
let some_arg_had_empty_expr_loc = ref false in
let rec loop args =
match args with
| {label = Some labelled; exp} :: rest ->
if
labelled.pos_start <= pos_before_cursor
&& pos_before_cursor < labelled.pos_end
then (
if Debug.verbose () then
print_endline "[findArgCompletables] Completing named arg #2";
Some (Completable.CnamedArg (context_path, labelled.name, all_names)))
else if exp.pexp_loc |> Loc.has_pos ~pos:pos_before_cursor then (
if Debug.verbose () then
print_endline
"[findArgCompletables] Completing in the assignment of labelled \
argument";
match
Completion_expressions.traverse_expr exp ~expr_path:[]
~pos:pos_before_cursor ~first_char_before_cursor_no_white
with
| None -> None
| Some (prefix, nested) ->
if Debug.verbose () then
print_endline
"[findArgCompletables] Completing for labelled argument value";
Some
(Cexpression
{
context_path =
CArgument
{
function_context_path = context_path;
argument_label = Labelled labelled.name;
};
prefix;
nested = List.rev nested;
}))
else if Completion_expressions.is_expr_hole exp then (
if Debug.verbose () then
print_endline "[findArgCompletables] found exprhole";
Some
(Cexpression
{
context_path =
CArgument
{
function_context_path = context_path;
argument_label = 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"
(Dump_ast.print_expr_item ~pos:pos_before_cursor ~indentation:0 exp);
(* Track whether there was an arg with an empty loc (indicates parser error)*)
if Cursor_position.loc_is_empty exp.pexp_loc ~pos:pos_before_cursor then
some_arg_had_empty_expr_loc := true;
if Res_parsetree_viewer.is_template_literal exp then None
else if exp.pexp_loc |> Loc.has_pos ~pos:pos_before_cursor then (
if Debug.verbose () then
print_endline
"[findArgCompletables] Completing in an unlabelled argument";
match
Completion_expressions.traverse_expr exp ~pos:pos_before_cursor
~first_char_before_cursor_no_white ~expr_path:[]
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
{
context_path =
CArgument
{
function_context_path = context_path;
argument_label =
Unlabelled {argument_position = !unlabelled_count};
};
prefix;
nested = List.rev nested;
}))
else if Completion_expressions.is_expr_hole exp then (
if Debug.verbose () then
print_endline "[findArgCompletables] found an exprhole #2";
Some
(Cexpression
{
context_path =
CArgument
{
function_context_path = context_path;
argument_label =
Unlabelled {argument_position = !unlabelled_count};
};
prefix = "";
nested = [];
}))
else (
unlabelled_count := !unlabelled_count + 1;
loop rest)
| [] ->
let had_empty_exp_loc = !some_arg_had_empty_expr_loc in
if fn_has_cursor then (
if Debug.verbose () then
print_endline "[findArgCompletables] Function has cursor";
match char_before_cursor with
| Some '~' ->
if Debug.verbose () then
print_endline "[findArgCompletables] '~' is before cursor";
Some (Completable.CnamedArg (context_path, "", all_names))
| _ when had_empty_exp_loc ->
(* 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 first_char_before_cursor_no_white = Some '('
|| first_char_before_cursor_no_white = 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"
is_piped_expr;
Some
(Cexpression
{
context_path =
CArgument
{
function_context_path = context_path;
argument_label =
Unlabelled {argument_position = !unlabelled_count};
};
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 fn_has_cursor ->
if Debug.verbose () then
print_endline "[findArgCompletables] Completing for unit argument";
Some
(Completable.Cexpression
{
context_path =
CArgument
{
function_context_path = context_path;
argument_label =
Unlabelled
{argument_position = (if is_piped_expr then 1 else 0)};
};
prefix = "";
nested = [];
})
| _ -> loop args
let rec expr_to_context_path_inner ~(in_jsx_context : bool)
(e : Parsetree.expression) =
match e.pexp_desc with
| Pexp_constant (Pconst_string _ | Pconst_raw_source _) ->
Some Completable.CPString
| Pexp_template _ -> Some Completable.CPString
| Pexp_tagged_template {tag} -> (
match expr_to_context_path ~in_jsx_context tag with
| Some context_path ->
(* Tagged templates are typed like a call of the tag with the template
strings and interpolation values. Preserve that application context
now that the parser no longer represents it as [Pexp_apply]. *)
Some (CPApply (context_path, [Nolabel; Nolabel]))
| None -> None)
| 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 :: _ -> expr_to_context_path ~in_jsx_context exp))
| Pexp_ident {txt = Lident "->"} -> None
| Pexp_ident {txt; loc} ->
Some
(CPId
{path = Utils.flatten_long_ident txt; completion_context = Value; loc})
| Pexp_field (e1, {txt = Lident name}) -> (
match expr_to_context_path ~in_jsx_context e1 with
| Some context_path ->
Some
(CPField
{
context_path;
field_name = name;
pos_of_dot = None;
expr_loc = e1.pexp_loc;
in_jsx = in_jsx_context;
})
| _ -> None)
| Pexp_field (e1, {loc; txt = Ldot (lid, name)}) ->
(* Case x.M.field ignore the x part *)
Some
(CPField
{
context_path =
CPId
{
path = Utils.flatten_long_ident lid;
completion_context = Module;
loc;
};
field_name = name;
pos_of_dot = None;
expr_loc = e1.pexp_loc;
in_jsx = in_jsx_context;
})
| Pexp_object_get (e1, {txt}) -> (
match expr_to_context_path ~in_jsx_context e1 with
| None -> None
| Some contex_path -> Some (CPObj (contex_path, txt)))
| Pexp_apply
{
funct =
{
pexp_desc = Pexp_ident {txt = Lident "->"};
pexp_loc;
pexp_attributes;
};
args =
[(_, lhs); (_, {pexp_desc = Pexp_apply {funct = d; args; partial}})];
transformed_jsx;
} ->
(* Transform away pipe with apply call *)
expr_to_context_path ~in_jsx_context
{
pexp_desc =
Pexp_apply
{funct = d; args = (Nolabel, lhs) :: args; partial; transformed_jsx};
pexp_loc;
pexp_attributes;
}
| Pexp_apply
({
funct = {pexp_desc = Pexp_ident {txt = Lident "->"}};
args =
[
(_, lhs);
(_, {pexp_desc = Pexp_ident id; pexp_loc; pexp_attributes});
];
} as app) ->
(* Transform away pipe with identifier *)
expr_to_context_path ~in_jsx_context
{
pexp_desc =
Pexp_apply
{
app with
funct = {pexp_desc = Pexp_ident id; pexp_loc; pexp_attributes};
args = [(Nolabel, lhs)];
};
pexp_loc;
pexp_attributes;
}
| Pexp_apply {funct = e1; args} -> (
match expr_to_context_path ~in_jsx_context e1 with
| None -> None
| Some contex_path -> Some (CPApply (contex_path, args |> List.map fst)))
| Pexp_tuple exprs ->
let exprs_as_context_paths =
exprs |> List.filter_map (expr_to_context_path ~in_jsx_context)
in
if List.length exprs = List.length exprs_as_context_paths then
Some (CTuple exprs_as_context_paths)
else None
| Pexp_await e -> expr_to_context_path_inner ~in_jsx_context e
| _ -> None
and expr_to_context_path ~(in_jsx_context : bool) (e : Parsetree.expression) =
match
( Res_parsetree_viewer.expr_is_await e,
expr_to_context_path_inner ~in_jsx_context e )
with
| true, Some ctx_path -> Some (CPAwait ctx_path)
| false, Some ctx_path -> Some ctx_path
| _, None -> None
let complete_pipe_chain ~(in_jsx_context : bool) (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->Array.filter(v => v > 10)->Array.map(v => v + 2)->
will complete as:
Array.map(someArray->Array.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->Array.map(v => v + 2)-> *)
| Pexp_apply
{
funct = {pexp_desc = Pexp_ident {txt = Lident "->"}};
args = [_; (_, {pexp_desc = Pexp_apply {funct = d}})];
} ->
expr_to_context_path ~in_jsx_context exp
|> Option.map (fun ctx_path -> (ctx_path, d.pexp_loc))
(* When the left side of the pipe we're completing is an identifier application.
Example: someArray->filterAllTheGoodStuff-> *)
| Pexp_apply
{
funct = {pexp_desc = Pexp_ident {txt = Lident "->"}};
args = [_; (_, {pexp_desc = Pexp_ident _; pexp_loc})];
} ->
expr_to_context_path ~in_jsx_context exp
|> Option.map (fun ctx_path -> (ctx_path, pexp_loc))
| _ -> None
let completion_with_parser1 ~debug ~offset ~pos_cursor ~kind_file
?find_this_expr_loc text =
let offset_no_white = Utils.skip_white text (offset - 1) in
let pos_no_white =
let line, col = pos_cursor in
(line, max 0 col - offset + offset_no_white)
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 first_char_before_cursor_no_white =
if offset_no_white < String.length text && offset_no_white >= 0 then
Some text.[offset_no_white]
else None
in
let pos_of_dot = Pos.pos_of_dot text ~pos:pos_cursor ~offset in
let char_at_cursor =
if offset >= 0 && offset < String.length text then text.[offset] else '\n'
in
let pos_before_cursor = Pos.pos_before_cursor pos_cursor in
let char_before_cursor, blank_after_cursor =
match Pos.position_to_offset text pos_cursor with
| Some offset when offset > 0 -> (
let char_before_cursor = text.[offset - 1] in
match char_at_cursor with
| ' ' | '\t' | '\r' | '\n' ->
(Some char_before_cursor, Some char_before_cursor)
| _ -> (Some char_before_cursor, None))
| _ -> (None, None)
in
let flatten_lid_check_dot ?(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 cut_at_offset =
let id_start = Loc.start lid.loc in
match blank_after_cursor with
| Some '.' ->
if fst pos_before_cursor = fst id_start then
Some (snd pos_before_cursor - snd id_start)
else None
| _ -> None
in
Utils.flatten_long_ident ~cut_at_offset ~jsx lid.txt
in
let current_ctx_path = ref None in
let processing_fun = ref None in
let set_current_ctx_path ctx_path =
if !Cfg.debug_follow_ctx_path then
Printf.printf "setting current ctxPath: %s\n"
(Completable.context_path_to_string ctx_path);
current_ctx_path := Some ctx_path
in
let reset_current_ctx_path ctx_path =
(match (!current_ctx_path, ctx_path) with
| None, None -> ()
| _ ->
if !Cfg.debug_follow_ctx_path then
Printf.printf "resetting current ctxPath to: %s\n"
(match ctx_path with
| None -> "None"
| Some ctx_path -> Completable.context_path_to_string ctx_path));
current_ctx_path := ctx_path
in
let found = ref false in
let result = ref None in
let scope = ref (Scope.create ()) in
let set_result_opt 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.to_string x);
result := Some (x, !scope)
in
let in_jsx_context = ref false in
let set_result x = set_result_opt (Some x) in
let scope_value_description (vd : Parsetree.value_description) =
scope :=
!scope |> Scope.add_value ~name:vd.pval_name.txt ~loc:vd.pval_name.loc
in
let rec scope_pattern ?context_path
?(pattern_path : Completable.nested_path list = [])
(pat : Parsetree.pattern) =
let context_path_to_save =
match (context_path, pattern_path) with
| maybe_context_path, [] -> maybe_context_path
| Some context_path, pattern_path ->
Some
(Completable.CPatternPath
{root_ctx_path = context_path; nested = List.rev pattern_path})
| _ -> None
in
match pat.ppat_desc with
| Ppat_any -> ()
| Ppat_var {txt; loc} ->
scope :=
!scope
|> Scope.add_value ~name:txt ~loc ?context_path:context_path_to_save
| Ppat_alias (p, as_a) ->
scope_pattern p ~pattern_path ?context_path;
let ctx_path =
if context_path_to_save = None then
match p with
| {ppat_desc = Ppat_var {txt; loc}} ->
Some
(Completable.CPId {path = [txt]; completion_context = Value; loc})
| _ -> None
else None
in
scope :=
!scope
|> Scope.add_value ~name:as_a.txt ~loc:as_a.loc ?context_path:ctx_path
| Ppat_constant _ | Ppat_interval _ -> ()
| Ppat_tuple pl ->
pl
|> List.iteri (fun index p ->
scope_pattern p
~pattern_path:(NTupleItem {item_num = index} :: pattern_path)
?context_path)
| Ppat_construct (_, None) -> ()
| Ppat_construct ({txt}, Some {ppat_desc = Ppat_tuple pl}) ->
pl
|> List.iteri (fun index p ->
scope_pattern p
~pattern_path:
(NVariantPayload
{
item_num = index;
constructor_name = Utils.get_unqualified_name txt;
}
:: pattern_path)
?context_path)
| Ppat_construct ({txt}, Some p) ->
scope_pattern
~pattern_path:
(NVariantPayload
{item_num = 0; constructor_name = Utils.get_unqualified_name txt}
:: pattern_path)
?context_path p
| Ppat_variant (_, None) -> ()
| Ppat_variant (txt, Some {ppat_desc = Ppat_tuple pl}) ->
pl
|> List.iteri (fun index p ->
scope_pattern p
~pattern_path:
(NPolyvariantPayload {item_num = index; constructor_name = txt}
:: pattern_path)
?context_path)
| Ppat_variant (txt, Some p) ->
scope_pattern
~pattern_path:
(NPolyvariantPayload {item_num = 0; constructor_name = txt}
:: pattern_path)
?context_path p
| Ppat_record (fields, _, rest) -> (
Ext_list.iter fields (fun {lid = fname; x = p} ->
match fname with
| {Location.txt = Longident.Lident fname} ->
scope_pattern
~pattern_path:
(Completable.NFollowRecordField {field_name = fname}
:: pattern_path)
?context_path p
| _ -> ());
match rest with
| None -> ()
| Some {rest_name = {txt; loc}; rest_type; _} ->
let context_path =
match rest_type with
| Some typ -> Type_utils.context_path_from_core_type typ
| None -> context_path_to_save
in
scope := !scope |> Scope.add_value ~name:txt ~loc ?context_path)
| Ppat_array pl ->
pl
|> List.iter
(scope_pattern ~pattern_path:(NArray :: pattern_path) ?context_path)
| Ppat_or (p1, _) -> scope_pattern ~pattern_path ?context_path p1
| Ppat_constraint (p, core_type) ->
scope_pattern ~pattern_path
?context_path:(Type_utils.context_path_from_core_type core_type)
p
| Ppat_type _ -> ()
| Ppat_unpack {txt; loc} ->
scope := !scope |> Scope.add_module ~name:txt ~loc
| Ppat_exception p -> scope_pattern ~pattern_path ?context_path p
| Ppat_extension _ -> ()
| Ppat_open (_, p) -> scope_pattern ~pattern_path ?context_path p
in
let loc_has_cursor = Cursor_position.loc_has_cursor ~pos:pos_before_cursor in
let loc_is_empty = Cursor_position.loc_is_empty ~pos:pos_before_cursor in
let complete_pattern ?context_path (pat : Parsetree.pattern) =
match
( pat
|> Completion_patterns.traverse_pattern ~pattern_path:[] ~loc_has_cursor
~first_char_before_cursor_no_white ~pos_before_cursor,
context_path )
with
| Some (prefix, nested_pattern), Some ctx_path ->
if Debug.verbose () then
Printf.printf "[completePattern] found pattern that can be completed\n";
set_result
(Completable.Cpattern
{
context_path = ctx_path;
prefix;
nested = List.rev nested_pattern;
fallback = None;
pattern_mode = Default;
})
| _ -> ()
in
let scope_value_binding (vb : Parsetree.value_binding) =
let context_path =
(* 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 complete_pipe_chain ~in_jsx_context:!in_jsx_context vb.pvb_expr with
| Some (ctx_path, _) -> Some ctx_path
| None -> expr_to_context_path ~in_jsx_context:!in_jsx_context vb.pvb_expr
in
scope_pattern ?context_path vb.pvb_pat
in
let scope_type_kind (tk : Parsetree.type_kind) =
match tk with
| Ptype_variant constr_decls ->
constr_decls
|> List.iter (fun (cd : Parsetree.constructor_declaration) ->
scope :=
!scope
|> Scope.add_constructor ~name:cd.pcd_name.txt ~loc:cd.pcd_loc)
| Ptype_record label_decls ->
label_decls
|> List.iter (fun (ld : Parsetree.label_declaration) ->
scope :=
!scope |> Scope.add_field ~name:ld.pld_name.txt ~loc:ld.pld_loc)
| _ -> ()
in
let scope_type_declaration (td : Parsetree.type_declaration) =
scope :=
!scope |> Scope.add_type ~name:td.ptype_name.txt ~loc:td.ptype_name.loc;
scope_type_kind td.ptype_kind
in
let scope_module_binding (mb : Parsetree.module_binding) =
scope :=
!scope |> Scope.add_module ~name:mb.pmb_name.txt ~loc:mb.pmb_name.loc
in
let scope_module_declaration (md : Parsetree.module_declaration) =
scope :=
!scope |> Scope.add_module ~name:md.pmd_name.txt ~loc:md.pmd_name.loc
in
(* Identifies expressions where we can do typed pattern or expr completion. *)
let typed_completion_expr (exp : Parsetree.expression) =
let debug_typed_completion_expr = false in
if exp.pexp_loc |> Cursor_position.loc_has_cursor ~pos:pos_before_cursor
then (
if Debug.verbose () && debug_typed_completion_expr 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 () && debug_typed_completion_expr then
print_endline "[typedCompletionExpr] No cases, with ident";
if loc_has_cursor expr.pexp_loc then (
if Debug.verbose () && debug_typed_completion_expr then
print_endline "[typedCompletionExpr] No cases - has cursor";
(* We can do exhaustive switch completion if this is an ident we can
complete from. *)
match expr_to_context_path ~in_jsx_context:!in_jsx_context expr with
| None -> ()
| Some context_path ->
set_result
(CexhaustiveSwitch {context_path; expr_loc = exp.pexp_loc}))
| Pexp_match (_expr, []) ->
(* switch x { } *)
if Debug.verbose () && debug_typed_completion_expr then
print_endline "[typedCompletionExpr] No cases, rest";
()
| Pexp_match (expr, [{pc_lhs; pc_rhs}])
when loc_has_cursor expr.pexp_loc
&& Completion_expressions.is_expr_hole pc_rhs
&& Completion_patterns.is_pattern_hole pc_lhs ->
(* switch x { | } when we're in the switch expr itself. *)
if Debug.verbose () && debug_typed_completion_expr 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 expr_to_context_path ~in_jsx_context:!in_jsx_context exp with
| None -> ()
| Some ctx_path ->
set_result
(Completable.Cpattern
{
context_path = ctx_path;
nested = [];
prefix = "";
fallback = None;
pattern_mode = Default;
}))
| Pexp_match (exp, cases) -> (
if Debug.verbose () && debug_typed_completion_expr 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 |> expr_to_context_path ~in_jsx_context:!in_jsx_context with
| None ->
if Debug.verbose () && debug_typed_completion_expr then
print_endline "[typedCompletionExpr] Has cases - no ctx path"
| Some ctx_path -> (
if Debug.verbose () && debug_typed_completion_expr then
print_endline "[typedCompletionExpr] Has cases - has ctx path";
let has_case_with_cursor =
cases
|> List.find_opt (fun case ->
loc_has_cursor case.Parsetree.pc_lhs.ppat_loc)
|> Option.is_some
in
let has_case_with_empty_loc =
cases
|> List.find_opt (fun case ->
loc_is_empty case.Parsetree.pc_lhs.ppat_loc)
|> Option.is_some
in
if Debug.verbose () && debug_typed_completion_expr then
Printf.printf
"[typedCompletionExpr] Has cases - has ctx path - \
hasCaseWithEmptyLoc: %b, hasCaseWithCursor: %b\n"
has_case_with_empty_loc has_case_with_cursor;
match (has_case_with_empty_loc, has_case_with_cursor) 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. *)
set_result
(Completable.Cpattern
{
context_path = ctx_path;
nested = [];
prefix = "";
fallback = None;
pattern_mode = Default;
})
| false, false -> ()))
| _ -> ())
in
let structure (iterator : Ast_iterator.iterator)
(structure : Parsetree.structure) =
let old_scope = !scope in
Ast_iterator.default_iterator.structure iterator structure;
scope := old_scope
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.add_open ~lid:popen_lid.txt
| Pstr_primitive vd -> scope_value_description vd
| Pstr_value (rec_flag, bindings) ->
if rec_flag = Recursive then bindings |> List.iter scope_value_binding;
bindings |> List.iter (fun vb -> iterator.value_binding iterator vb);
if rec_flag = Nonrecursive then bindings |> List.iter scope_value_binding;
processed := true
| Pstr_type (rec_flag, decls) ->
if rec_flag = Recursive then decls |> List.iter scope_type_declaration;
decls |> List.iter (fun td -> iterator.type_declaration iterator td);
if rec_flag = Nonrecursive then decls |> List.iter scope_type_declaration;
processed := true
| Pstr_module mb ->
iterator.module_binding iterator mb;
scope_module_binding mb;
processed := true
| Pstr_recmodule mbs ->
mbs |> List.iter scope_module_binding;
mbs |> List.iter (fun b -> iterator.module_binding iterator b);
processed := true
| Pstr_include {pincl_mod = {pmod_desc = med}} -> (
match med with
| Pmod_ident {txt = lid; loc}
| Pmod_apply ({pmod_desc = Pmod_ident {txt = lid; loc}}, _) ->
let module_name = Longident.flatten lid |> String.concat "." in
scope := !scope |> Scope.add_include ~name:module_name ~loc
| _ -> ())
| _ -> ());
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 old_in_jsx_context = !in_jsx_context in
if Utils.is_jsx_component value_binding then in_jsx_context := true;
(match value_binding with
| {pvb_pat = {ppat_desc = Ppat_constraint (_, core_type)}; pvb_expr}
| {pvb_constraint = Some {pvc_type = core_type}; pvb_expr}
when loc_has_cursor pvb_expr.pexp_loc -> (
(* Expression with derivable type annotation.
E.g: let x: someRecord = {<com>} *)
match
( Type_utils.context_path_from_core_type core_type,
pvb_expr
|> Completion_expressions.traverse_expr ~expr_path:[]
~pos:pos_before_cursor ~first_char_before_cursor_no_white )
with
| Some ctx_path, Some (prefix, nested) ->
set_result
(Completable.Cexpression
{context_path = ctx_path; prefix; nested = List.rev nested})
| _ -> ())
| {pvb_pat = {ppat_desc = Ppat_var {loc}}; pvb_expr}
when loc_has_cursor 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
|> Completion_expressions.traverse_expr ~expr_path:[]
~pos:pos_before_cursor ~first_char_before_cursor_no_white
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;
set_result
(Completable.Cexpression
{context_path = CTypeAtPos loc; prefix; nested = List.rev nested})
| _ -> ())
| {
pvb_pat = {ppat_desc = Ppat_constraint (_, core_type); ppat_loc};
pvb_expr;
}
| {
pvb_pat = {ppat_loc};
pvb_expr;
pvb_constraint = Some {pvc_type = core_type};
}
when loc_has_cursor value_binding.pvb_loc
&& loc_has_cursor ppat_loc = false
&& loc_has_cursor pvb_expr.pexp_loc = false
&& Completion_expressions.is_expr_hole pvb_expr -> (
(* Expression with derivable type annotation, when the expression is empty (expr hole).
E.g: let x: someRecord = <com> *)
match Type_utils.context_path_from_core_type core_type with
| Some ctx_path ->
set_result
(Completable.Cexpression
{context_path = ctx_path; prefix = ""; nested = []})
| _ -> ())
| {pvb_pat; pvb_expr} when loc_has_cursor pvb_pat.ppat_loc -> (
(* Completing a destructuring.
E.g: let {<com>} = someVar *)
match
( pvb_pat
|> Completion_patterns.traverse_pattern ~pattern_path:[]
~loc_has_cursor ~first_char_before_cursor_no_white
~pos_before_cursor,
expr_to_context_path ~in_jsx_context:!in_jsx_context pvb_expr )
with
| Some (prefix, nested), Some ctx_path ->
set_result
(Completable.Cpattern
{
context_path = ctx_path;
prefix;
nested = List.rev nested;
fallback = None;
pattern_mode = Destructuring;
})
| _ -> ())
| _ -> ());
Ast_iterator.default_iterator.value_binding iterator value_binding;
in_jsx_context := old_in_jsx_context
in
let signature (iterator : Ast_iterator.iterator)
(signature : Parsetree.signature) =
let old_scope = !scope in
Ast_iterator.default_iterator.signature iterator signature;
scope := old_scope
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.add_open ~lid:popen_lid.txt
| Psig_value vd -> scope_value_description vd
| Psig_type (rec_flag, decls) ->
if rec_flag = Recursive then decls |> List.iter scope_type_declaration;
decls |> List.iter (fun td -> iterator.type_declaration iterator td);
if rec_flag = Nonrecursive then decls |> List.iter scope_type_declaration;
processed := true
| Psig_module md ->
iterator.module_declaration iterator md;
scope_module_declaration md;
processed := true
| Psig_recmodule mds ->
mds |> List.iter scope_module_declaration;
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.has_pos ~pos:pos_before_cursor then
let pos_start, pos_end = Loc.range id.loc in
match
( Pos.position_to_offset text pos_start,
Pos.position_to_offset text pos_end )
with
| Some offset_start, Some offset_end
when offset_start >= 0 && offset_end >= offset_start ->
(* Can't trust the parser's location
E.g. @foo. let x... gives as label @foo.let *)
let label =
let raw_label =
String.sub text offset_start (offset_end - offset_start)
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 raw_label ' '
++ String.index_opt raw_label '\t'
++ String.index_opt raw_label '\r'
++ String.index_opt raw_label '\n'
with
| None -> raw_label
| Some i -> String.sub raw_label 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.to_string id.loc) label;
set_result (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 _)
| Pexp_template {source_segments = [_]; values = []} );
} as expression),
_ );
};
]
when loc_has_cursor pexp_loc -> (
match Ast_payload.semantic_string_of_expression expression with
| Some s ->
if Debug.verbose () then
print_endline "[decoratorCompletion] Found @module";
set_result (Completable.CdecoratorPayload (Module s))
| None -> ())
| PStr
[
{
pstr_desc =
Pstr_eval
( {
pexp_desc =
Pexp_record
({lid = {txt = Lident "from"}; x = from_expr} :: _, _);
},
_ );
};
]
when loc_has_cursor from_expr.pexp_loc
|| loc_is_empty from_expr.pexp_loc
&& Completion_expressions.is_expr_hole from_expr -> (
if Debug.verbose () then
print_endline
"[decoratorCompletion] Found @module with import attributes and \
cursor on \"from\"";
match
( loc_has_cursor from_expr.pexp_loc,
loc_is_empty from_expr.pexp_loc,
Completion_expressions.is_expr_hole from_expr,
from_expr )
with
| true, _, _, from_expr -> (
match Ast_payload.semantic_string_of_expression from_expr with
| Some s ->
if Debug.verbose () then
print_endline
"[decoratorCompletion] @module `from` payload was string";
set_result (Completable.CdecoratorPayload (Module s))
| None -> ())
| false, true, true, _ ->
if Debug.verbose () then
print_endline
"[decoratorCompletion] @module `from` payload was expr hole";