Skip to content

Commit 98ecc79

Browse files
cknittclaude
andcommitted
Complete the constructors of extensible variants
Why: Editor analysis didn't record the constructors added by `type t += ...`, and an open type has none in its declaration, so completion offered no constructor where a value of the type was expected. They are now registered as constructors of an open type, and typed completion of an open type offers those declared in the type's file and in the current file. Since other files can extend the type, the exhaustive switch snippet for one adds a `_` case. Diagnostic modified (completion of an extensible variant): Example: type attr = .. type attr += Str(string) | Num(int) // let a: attr = Nu Before (text): tests/analysis_tests/tests/src/CompletionExtensibleVariant.res Nullable, Null After (text): tests/analysis_tests/tests/src/CompletionExtensibleVariant.res Num(_), Nullable, Null Diagnostic modified (exhaustive switch snippet): Example: let value: attr = Str("s") // switch valu After (rescript): switch value { | Str(_) => %todo | Num(_) => %todo | Flag => %todo | _ => %todo } Review: Which extensions are offered? Those in the file that declares the type and in the current file; an extension in a third file is not known to the current file's analysis. Fixes: #9073 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Kbf3gLMawVgtmiKy3TMBc3 Signed-off-by: Christoph Knittel <ck@cca.io>
1 parent cd641cb commit 98ecc79

6 files changed

Lines changed: 217 additions & 9 deletions

File tree

‎analysis/src/completion_back_end.ml‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2569,15 +2569,23 @@ let rec process_completable ~state ~debug ~full ~scope ~env ~pos ~for_hover
25692569
typ_expr |> Type_utils.extract_type ~env:c.env ~package ~state
25702570
with
25712571
| Some (Tvariant v, _) ->
2572-
with_exhaustive_item c
2573-
~cases:
2574-
(v.constructors
2575-
|> List.map (fun (constructor : Constructor.t) ->
2576-
constructor.cname.txt
2577-
^
2578-
match constructor.args with
2579-
| Args [] -> ""
2580-
| _ -> "(_)"))
2572+
let cases =
2573+
v.constructors
2574+
|> List.map (fun (constructor : Constructor.t) ->
2575+
constructor.cname.txt
2576+
^
2577+
match constructor.args with
2578+
| Args [] -> ""
2579+
| _ -> "(_)")
2580+
in
2581+
(* An open type can be extended elsewhere, so only a catch-all
2582+
case makes the switch exhaustive. *)
2583+
let cases =
2584+
match v.variant_decl.type_kind with
2585+
| Type_open -> cases @ ["_"]
2586+
| _ -> cases
2587+
in
2588+
with_exhaustive_item c ~cases
25812589
| Some (Tpolyvariant v, _) ->
25822590
with_exhaustive_item c
25832591
~cases:

‎analysis/src/process_cmt.ml‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,60 @@ let for_type_declaration ~env ~(exported : Exported.t)
328328
loc = declared.extent_loc;
329329
}
330330

331+
(* The constructors of [type t += ...] are registered as constructors of an
332+
open type named [t], so that completion can offer them for values of
333+
type [t]. They are not part of any type declaration, hence the stand-in
334+
declaration that only carries the kind. *)
335+
let add_extension_constructors ~(env : Env.t)
336+
{Typedtree.tyext_path; tyext_constructors} =
337+
let type_name = Path.last tyext_path in
338+
let type_decl : Types.type_declaration =
339+
{
340+
type_params = [];
341+
type_arity = 0;
342+
type_kind = Type_open;
343+
type_private = Public;
344+
type_manifest = None;
345+
type_variance = [];
346+
type_newtype_level = None;
347+
type_loc = Location.none;
348+
type_attributes = [];
349+
type_immediate = false;
350+
type_representation = Boxed;
351+
type_shape = Unstated;
352+
type_inlined_types = [];
353+
}
354+
in
355+
tyext_constructors
356+
|> List.iter
357+
(fun
358+
({ext_id; ext_name; ext_type; ext_loc; ext_attributes} :
359+
Typedtree.extension_constructor)
360+
->
361+
let stamp = Ident.binding_time ext_id in
362+
let item =
363+
{
364+
Constructor.stamp;
365+
cname = ext_name;
366+
args =
367+
(match ext_type.ext_args with
368+
| Cstr_tuple args ->
369+
Args (args |> List.map (fun t -> (t, Location.none)))
370+
| Cstr_record fields ->
371+
InlineRecord (fields |> List.map map_record_field));
372+
res = ext_type.ext_ret_type;
373+
type_decl = (type_name, type_decl);
374+
docstring = attrs_to_docstring ext_attributes;
375+
deprecated =
376+
Process_attributes.find_deprecated_attribute ext_attributes;
377+
}
378+
in
379+
let declared =
380+
Process_attributes.new_declared ~item ~extent:ext_loc ~name:ext_name
381+
~stamp ~module_path:env.module_path true ext_attributes
382+
in
383+
Stamps.add_constructor env.stamps stamp declared)
384+
331385
let rec for_signature_item ~env ~(exported : Exported.t)
332386
(item : Typedtree.signature_item) =
333387
match item.sig_desc with
@@ -401,6 +455,9 @@ let rec for_signature_item ~env ~(exported : Exported.t)
401455
incl_type []
402456
in
403457
top_level
458+
| Tsig_typext type_extension ->
459+
add_extension_constructors ~env type_extension;
460+
[]
404461
(* TODO: process other things here *)
405462
| _ -> []
406463

@@ -645,6 +702,9 @@ let rec for_structure_item ~(env : Shared_types.Env.t) ~(exported : Exported.t)
645702
| _ -> Types.Trec_next
646703
in
647704
decl |> for_type_declaration ~env ~exported ~rec_status)
705+
| Tstr_typext type_extension ->
706+
add_extension_constructors ~env type_extension;
707+
[]
648708
| _ -> []
649709

650710
and for_module ~env mod_desc module_name =

‎analysis/src/type_utils.ml‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,27 @@ let extract_function_type2 ?type_arg_context ~state ~env ~package typ =
361361
in
362362
loop ?type_arg_context ~env [] typ
363363

364+
(* The constructors of an open type are those of its extensions, here the
365+
ones in the given files. *)
366+
let extension_constructors ~(files : File.t list) ~type_name ~decl =
367+
let found = Hashtbl.create 8 in
368+
files
369+
|> List.iter (fun (file : File.t) ->
370+
file.stamps
371+
|> Stamps.iter_constructors
372+
(fun stamp (declared : Constructor.t Declared.t) ->
373+
let name, ext_decl = declared.item.type_decl in
374+
if name = type_name && ext_decl.type_kind = Type_open then
375+
Hashtbl.replace found (file.uri, stamp) declared.item));
376+
Hashtbl.to_seq_values found
377+
|> List.of_seq
378+
|> List.sort (fun (a : Constructor.t) (b : Constructor.t) ->
379+
compare
380+
(a.cname.loc.loc_start.pos_fname, a.cname.loc.loc_start.pos_cnum)
381+
(b.cname.loc.loc_start.pos_fname, b.cname.loc.loc_start.pos_cnum))
382+
|> List.map (fun (c : Constructor.t) ->
383+
{c with type_decl = (type_name, decl)})
384+
364385
let rec extract_type ?(print_opening_debug = true)
365386
?(type_arg_context : type_arg_context option)
366387
?(type_arg_context_from_type_manifest : type_arg_context option) ~env ~state
@@ -445,6 +466,28 @@ let rec extract_type ?(print_opening_debug = true)
445466
variant_decl = decl;
446467
},
447468
type_arg_context )
469+
| Some (env_from_item, {name; item = {decl; kind = Type.Open}})
470+
when decl.type_manifest = None -> (
471+
let type_arg_context =
472+
maybe_set_type_arg_ctx ~type_params:decl.type_params ~type_args env
473+
in
474+
match
475+
extension_constructors ~files:[env_from_item.file] ~type_name:name.txt
476+
~decl
477+
with
478+
| [] when name.txt = "t" ->
479+
Some (TtypeT {env = env_from_item; path}, type_arg_context)
480+
| [] -> None
481+
| constructors ->
482+
Some
483+
( Tvariant
484+
{
485+
env = env_from_item;
486+
constructors;
487+
variant_name = name.txt;
488+
variant_decl = decl;
489+
},
490+
type_arg_context ))
448491
| Some (env_from_declaration, {item = {kind = Record fields; decl}}) ->
449492
if Debug.verbose () then print_endline "[extract_type]--> found record";
450493
(* Need to create a new type arg context here because we're sending along a type expr that might have type vars. *)
@@ -601,6 +644,17 @@ let extract_type_from_resolved_type (typ : Type.t) ~env ~full ~state =
601644
Some
602645
(Tvariant
603646
{env; constructors; variant_name = typ.name; variant_decl = typ.decl})
647+
| Open when typ.decl.type_manifest = None -> (
648+
match
649+
extension_constructors ~files:[env.file; full.file] ~type_name:typ.name
650+
~decl:typ.decl
651+
with
652+
| [] -> None
653+
| constructors ->
654+
Some
655+
(Tvariant
656+
{env; constructors; variant_name = typ.name; variant_decl = typ.decl})
657+
)
604658
| Abstract _ | Open -> (
605659
match typ.decl.type_manifest with
606660
| None -> None
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- Editor completion offers the constructors of an extensible variant declared in the current file or in the type's file, and the exhaustive switch snippet for one ends with a `_` case.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
type attr = ..
2+
type attr += Str(string) | Num(int)
3+
4+
module Sub = {
5+
type attr += Flag
6+
}
7+
8+
// let a: attr = Nu
9+
// ^com
10+
11+
let value: attr = Str("s")
12+
13+
// switch value { | S
14+
// ^com
15+
16+
// switch valu
17+
// ^com
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
Complete src/CompletionExtensibleVariant.res 7:19
2+
XXX Not found!
3+
Completable: Cexpression Type[attr]=Nu
4+
Package opens Stdlib.place holder Pervasives.JsxModules.place holder
5+
Resolved opens 1 Stdlib
6+
ContextPath Type[attr]
7+
Path attr
8+
[
9+
{
10+
"detail": "Num(int)",
11+
"documentation": {
12+
"kind": "markdown",
13+
"value": "```rescript\nNum(int)\n```\n\n```rescript\ntype attr = ..\n```"
14+
},
15+
"insertText": "Num($0)",
16+
"insertTextFormat": 2,
17+
"kind": 4,
18+
"label": "Num(_)",
19+
"sortText": "A Num(_)",
20+
"tags": []
21+
},
22+
{ "detail": "module Nullable", "kind": 9, "label": "Nullable", "tags": [] },
23+
{ "detail": "module Null", "kind": 9, "label": "Null", "tags": [] }
24+
]
25+
26+
Complete src/CompletionExtensibleVariant.res 12:21
27+
pos_cursor:[12:21] pos_no_white:[12:20] Found pattern:[12:20->12:21]
28+
Ppat_construct S:[12:20->12:21]
29+
Completable: Cpattern Value[value]=S
30+
Package opens Stdlib.place holder Pervasives.JsxModules.place holder
31+
Resolved opens 1 Stdlib
32+
ContextPath Value[value]
33+
Path value
34+
[
35+
{
36+
"detail": "Str(string)",
37+
"documentation": {
38+
"kind": "markdown",
39+
"value": "```rescript\nStr(string)\n```\n\n```rescript\ntype attr = ..\n```"
40+
},
41+
"insertText": "Str(${1:_})",
42+
"insertTextFormat": 2,
43+
"kind": 4,
44+
"label": "Str(_)",
45+
"tags": []
46+
}
47+
]
48+
49+
Complete src/CompletionExtensibleVariant.res 15:14
50+
XXX Not found!
51+
Completable: CexhaustiveSwitch Value[valu]
52+
Package opens Stdlib.place holder Pervasives.JsxModules.place holder
53+
Resolved opens 1 Stdlib
54+
ContextPath Value[valu]
55+
Path valu
56+
[
57+
{ "detail": "attr", "kind": 12, "label": "value", "tags": [] },
58+
{
59+
"detail": "insert exhaustive switch for value",
60+
"filterText": "value",
61+
"insertText": "value {\n | Str(_) => ${1:%todo}\n | Num(_) => ${2:%todo}\n | Flag => ${3:%todo}\n | _ => ${4:%todo}\n }",
62+
"insertTextFormat": 2,
63+
"kind": 15,
64+
"label": "value (exhaustive switch)",
65+
"tags": []
66+
}
67+
]
68+

0 commit comments

Comments
 (0)