Skip to content

Commit d48780b

Browse files
cknittclaude
andcommitted
Read the three runtime annotations on one path
Why: `@notUndefined` was parsed, checked on declarations and checked on abbreviations apart from `@instanceOf` and `@typeOf`, so each step had two versions, and a type could carry it beside the others. `process_runtime_annotation` returns `Not_undefined` as well, so one parse feeds `declaration_shape`, the check for represented types and `Typedecl.check_manifest_annotation`, which now checks all three on an abbreviation. `Typeopt.abstractness` takes a type and is what `undefinedness` falls back to. Diagnostic changed (two of the three annotations): Example: @notundefined @typeof("string") type t Before (diagnostic): none After (diagnostic): A type can have only one of @notundefined, @instanceof and @typeof. @instanceof and @typeof already imply @notundefined. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CMkrYaktctdKc4M41WF36t Signed-off-by: Christoph Knittel <ck@cca.io>
1 parent 252774a commit d48780b

9 files changed

Lines changed: 136 additions & 137 deletions

‎compiler/ml/UntaggedVariants.md‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ level implying the one before:
139139
- `@instanceOf("C")`: they are instances of the global class at the path `C`,
140140
such as `"Date"` or `"Intl.Locale"`.
141141

142-
A type has at most one of `@typeOf` and `@instanceOf`, and only abstract types
143-
and type abbreviations, public or private, can have any of the three.
142+
A type has at most one of the three, and only abstract types and type
143+
abbreviations, public or private, can have one.
144144
`@notUndefined` affects only rule 12: `option` of the type, and of an untagged
145145
variant with a payload of the type, is unboxed. It does not make the type a
146146
recognized payload kind (rule 4).
@@ -189,7 +189,7 @@ would `type dog = animal<int>` or `type dog = phantom<int>` with
189189
| `@instanceOf("Dog") type dog = animal`, `= animal<int>`, or `= phantom<int>` with `type phantom<'a> = animal` | A subclass must be a private abbreviation ... | `instance_of_public_subclass.res`, `instance_of_public_subclass_instance.res`, `instance_of_public_subclass_through_alias.res` |
190190
| `@instanceOf("Animal") type t = private dog` | Animal appears twice in this chain of abbreviations ... | `instance_of_class_twice_in_chain.res` |
191191
| any of the three on a record or variant | @instanceOf can only be used on abstract types and type abbreviations ... | `runtime_annotation_on_record.res`, `invalid_attribute_not_undefined.res` |
192-
| both `@instanceOf` and `@typeOf` | A type can have either @instanceOf or @typeOf, not both. | `runtime_annotation_conflict.res` |
192+
| two of the three | A type can have only one of @notUndefined, @instanceOf and @typeOf. ... | `runtime_annotation_conflict.res`, `runtime_annotation_not_undefined_conflict.res` |
193193
| one annotation twice | Duplicate @instanceOf annotation; a type can have only one. | `instance_of_duplicate.res` |
194194

195195
What an interface states about a type must hold for its implementation. A
@@ -249,9 +249,9 @@ written (Known bugs).
249249

250250
- Implementation: `types.mli:type_shape`,
251251
`variant_runtime.mli:value_shape`; `variant_layout.ml:declaration_shape`,
252-
`resolve_shapes`, `value_shape`, `check_manifest_annotation`;
253-
`typedecl.ml:check_manifest_annotations`; `typeopt.ml:undefinedness`;
254-
`ast_untagged_variants.ml:process_runtime_annotation`, `has_not_undefined`,
252+
`resolve_shapes`, `value_shape`, `payload_kind`;
253+
`typedecl.ml:check_manifest_annotation`; `typeopt.ml:abstractness`,
254+
`undefinedness`; `ast_untagged_variants.ml:process_runtime_annotation`,
255255
`unsupported_class`, `check_runtime_annotation`;
256256
`includecore.ml:compare_runtime_annotations`;
257257
`variant_runtime.ml:Instance`; `js_exp_make.ml:class_constructor`.

‎compiler/ml/ast_untagged_variants.ml‎

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,9 @@ let report_error ppf =
148148
for another one, whose values can be anything."
149149
attribute
150150
| ConflictingRuntimeAnnotations ->
151-
fprintf ppf "A type can have either @instanceOf or @typeOf, not both."
151+
fprintf ppf
152+
"A type can have only one of @notUndefined, @instanceOf and @typeOf. \
153+
@instanceOf and @typeOf already imply @notUndefined."
152154
| RuntimeAnnotationOnRepresentedType attribute ->
153155
fprintf ppf
154156
"@%s can only be used on abstract types and type abbreviations, whose \
@@ -242,12 +244,14 @@ let report_constructor_more_than_one_arg ~loc ~name =
242244
(Error
243245
(loc, InvalidUntaggedVariantDefinition (ConstructorMoreThanOneArg name)))
244246

245-
(* What [@instanceOf] or [@typeOf] on a type declaration states about the
246-
runtime representation of its values. *)
247+
(* What [@notUndefined], [@instanceOf] or [@typeOf] on a type declaration
248+
states about the runtime representation of its values. *)
247249
type runtime_annotation =
250+
| Not_undefined (** values that are never [undefined] *)
248251
| Instance_of of string (** instances of the global class at this path *)
249252
| Type_of of block_type (** values with this [typeof] *)
250253

254+
let not_undefined = "notUndefined"
251255
let instance_of = "instanceOf"
252256
let type_of = "typeOf"
253257

@@ -294,6 +298,7 @@ let is_class_path name =
294298
| [] -> false
295299

296300
let runtime_attribute_name = function
301+
| Not_undefined -> not_undefined
297302
| Instance_of _ -> instance_of
298303
| Type_of _ -> type_of
299304

@@ -302,6 +307,7 @@ let typeof_name block_type =
302307
Option.value (Variant_runtime.typeof_name block_type) ~default:"object"
303308

304309
let runtime_annotation_to_string = function
310+
| Not_undefined -> "@" ^ not_undefined
305311
| Instance_of name -> Printf.sprintf "@%s(\"%s\")" instance_of name
306312
| Type_of block_type ->
307313
Printf.sprintf "@%s(\"%s\")" type_of (typeof_name block_type)
@@ -317,16 +323,15 @@ let describe_declared_block_type = function
317323
"values whose typeof is \"" ^ typeof_name block_type ^ "\""
318324
| None -> "no runtime class or typeof"
319325

320-
let has_not_undefined (attrs : Parsetree.attributes) =
321-
Ext_list.exists attrs (fun ({txt}, _) -> txt = "notUndefined")
322-
323-
(* The [@instanceOf] or [@typeOf] annotation in [attrs], validated. Only
324-
[Typedecl] passes [~loc]; later readers see attributes it accepted. *)
326+
(* The [@notUndefined], [@instanceOf] or [@typeOf] annotation in [attrs],
327+
validated. Only [Typedecl] passes [~loc]; later readers see attributes it
328+
accepted. *)
325329
let process_runtime_annotation ?(loc = Location.none)
326330
(attrs : Parsetree.attributes) =
327331
let annotation_of ({Location.txt; loc = attr_loc}, payload) =
328332
let loc = if attr_loc = Location.none then loc else attr_loc in
329-
if txt = instance_of then
333+
if txt = not_undefined then Some Not_undefined
334+
else if txt = instance_of then
330335
match Ast_payload.semantic_string_of_payload payload with
331336
| Some name when is_class_path name -> (
332337
match unsupported_class name with

‎compiler/ml/typedecl.ml‎

Lines changed: 63 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -336,35 +336,69 @@ let make_constructor env type_path type_params sargs sret_type =
336336
any type variable present in [ty].
337337
*)
338338

339-
(* [@notUndefined] on an abbreviation is a claim about the abbreviated type,
340-
as [@instanceOf] and [@typeOf] are: it can refine a type whose
341-
representation the compiler does not see, or restate that a type cannot
342-
hold [undefined] *)
343-
let check_not_undefined_manifest ~loc ~env (decl : Types.type_declaration) =
344-
match decl.type_manifest with
345-
| Some manifest
346-
when Ast_untagged_variants.has_not_undefined decl.type_attributes -> (
347-
let error err = raise (Ast_untagged_variants.Error (loc, err)) in
348-
match Typeopt.undefinedness env manifest with
349-
| Cannot_be_undefined | Unseen -> ()
350-
| Stands_for_another ->
351-
error (RuntimeAnnotationOnTypeParameter "notUndefined")
352-
| Can_be_undefined ->
353-
error (RuntimeAnnotationOnUnrelatedType "notUndefined"))
354-
| Some _ | None -> ()
355-
356-
let check_manifest_annotations ~loc ~env decl =
357-
Variant_layout.check_manifest_annotation ~loc ~env decl;
358-
check_not_undefined_manifest ~loc ~env decl
339+
(* An annotation on an abbreviation is a claim about the abbreviated type, so
340+
it must agree with what the compiler knows about that type. It can refine
341+
an abstract type, restate what the abbreviated type is known to be, or, on
342+
a private abbreviation, declare a subclass of the class annotated there.
343+
Anything else, such as [@typeOf("string") type t = option<string>], would
344+
let two spellings of one type be recognized differently, and would make
345+
[Some(None)] of a type that can be undefined indistinguishable from
346+
[None]. *)
347+
let check_manifest_annotation ~loc ~env (decl : Types.type_declaration) =
348+
let open Ast_untagged_variants in
349+
let open Variant_runtime in
350+
match
351+
(process_runtime_annotation decl.type_attributes, decl.type_manifest)
352+
with
353+
| None, _ | Some _, None -> ()
354+
| Some outer, Some manifest -> (
355+
let error err = raise (Error (loc, err)) in
356+
let stands_for_another () =
357+
error (RuntimeAnnotationOnTypeParameter (runtime_attribute_name outer))
358+
in
359+
let unrelated () =
360+
error (RuntimeAnnotationOnUnrelatedType (runtime_attribute_name outer))
361+
in
362+
match (outer, Variant_layout.payload_kind ~env manifest) with
363+
| Not_undefined, _ -> (
364+
match Typeopt.undefinedness env manifest with
365+
| Cannot_be_undefined | Unseen -> ()
366+
| Stands_for_another -> stands_for_another ()
367+
| Can_be_undefined -> unrelated ())
368+
| (Instance_of _ | Type_of _), None -> (
369+
match Typeopt.abstractness env manifest with
370+
| Opaque -> ()
371+
| Stands_for_another -> stands_for_another ()
372+
| Not_abstract -> unrelated ())
373+
| Type_of block_type, Some inner when block_type = inner -> ()
374+
| Instance_of name, Some (InstanceType (Class {name = inner}))
375+
when name = inner ->
376+
()
377+
| Instance_of name, Some ((InstanceType (Class _) | ObjectType) as inner) ->
378+
(* A public abbreviation would make every value of the superclass type
379+
a value of the subclass, without a coercion *)
380+
let superclass, ancestors =
381+
match inner with
382+
| InstanceType (Class {name = ancestor; ancestors}) ->
383+
(ancestor, ancestor :: ancestors)
384+
(* Every class instance is an object *)
385+
| _ -> ("Object", [])
386+
in
387+
if decl.type_private = Public then
388+
error (SubclassOfPublicAbbreviation (name, superclass))
389+
else if List.mem name ancestors then error (ClassTwiceInChain name)
390+
| (Instance_of _ | Type_of _), Some inner ->
391+
let inner =
392+
match inner with
393+
| InstanceType (Class {name}) -> Instance_of name
394+
| block_type -> Type_of block_type
395+
in
396+
error
397+
(RuntimeAnnotationContradictsManifest
398+
( runtime_annotation_to_string outer,
399+
runtime_annotation_to_string inner )))
359400

360401
let transl_declaration ~type_record_as_object env sdecl id =
361-
if
362-
Ast_untagged_variants.has_not_undefined sdecl.ptype_attributes
363-
&& sdecl.ptype_kind <> Ptype_abstract
364-
then
365-
raise
366-
(Ast_untagged_variants.Error
367-
(sdecl.ptype_loc, RuntimeAnnotationOnRepresentedType "notUndefined"));
368402
Ast_untagged_variants.check_runtime_annotation ~loc:sdecl.ptype_loc
369403
~is_abstract_or_abbreviation:(sdecl.ptype_kind = Ptype_abstract)
370404
sdecl.ptype_attributes;
@@ -1605,7 +1639,7 @@ let transl_type_decl env rec_flag sdecl_list =
16051639
in
16061640
List.iter2
16071641
(fun sdecl (_, decl) ->
1608-
check_manifest_annotations ~loc:sdecl.ptype_loc ~env:newenv decl)
1642+
check_manifest_annotation ~loc:sdecl.ptype_loc ~env:newenv decl)
16091643
sdecl_list decls;
16101644
List.iter2 (check_constraints ~type_record_as_object newenv) sdecl_list decls;
16111645
(* Name recursion *)
@@ -2018,7 +2052,7 @@ let transl_with_constraint env id row_path orig_decl sdecl =
20182052
let decl =
20192053
{decl with type_shape = Variant_layout.declaration_shape ~env decl}
20202054
in
2021-
check_manifest_annotations ~loc:sdecl.ptype_loc ~env decl;
2055+
check_manifest_annotation ~loc:sdecl.ptype_loc ~env decl;
20222056
let decl = name_recursion sdecl id decl in
20232057
let type_variance =
20242058
compute_variance_decl env true decl

‎compiler/ml/typeopt.ml‎

Lines changed: 30 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -122,27 +122,45 @@ let rec cannot_contain_undefined ~visiting (typ : Types.type_expr) (env : Env.t)
122122
let type_cannot_contain_undefined typ env =
123123
cannot_contain_undefined ~visiting:[] typ env
124124

125+
type abstractness = Opaque | Stands_for_another | Not_abstract
126+
127+
(* Whether [ty] is, also through abbreviations, an abstract type with a
128+
representation of its own, which an annotation can refine, or one that
129+
stands for another type: a functor parameter's type, a recursive module's
130+
type being defined, or a locally abstract type. *)
131+
let abstractness env ty =
132+
match (Ctype.expand_head_opt env ty).desc with
133+
| Tconstr (path, _, _) -> (
134+
match Env.find_type path env with
135+
| {type_kind = Type_abstract; type_manifest = None; type_newtype_level} ->
136+
if type_newtype_level <> None || Env.is_functor_arg path env then
137+
Stands_for_another
138+
else if Predef.type_is_builtin_path_but_option path <> Predef.NA then
139+
Not_abstract
140+
else Opaque
141+
| _ -> Not_abstract
142+
| exception Not_found -> Not_abstract)
143+
| _ -> Not_abstract
144+
125145
type undefinedness =
126146
| Cannot_be_undefined
127147
| Unseen
128148
| Stands_for_another
129149
| Can_be_undefined
130150

131151
(* Whether a type can hold [undefined], as far as the compiler sees. An
132-
abstract type, also through an abbreviation, or a JavaScript object type
133-
has a representation the compiler does not see; a functor parameter's or a
134-
locally abstract type stands for any type. *)
135-
let undefinedness env ty =
152+
opaque abstract type or a JavaScript object type has a representation the
153+
compiler does not see. *)
154+
let undefinedness env ty : undefinedness =
136155
if type_cannot_contain_undefined ty env then Cannot_be_undefined
137156
else
138-
match (Ctype.expand_head_opt env ty).desc with
139-
| Tconstr (path, _, _) -> (
140-
match Variant_layout.abstractness ~env path with
141-
| Opaque -> Unseen
142-
| Stands_for_another -> Stands_for_another
143-
| Not_abstract -> Can_be_undefined)
144-
| Tobject _ -> Unseen
145-
| _ -> Can_be_undefined
157+
match abstractness env ty with
158+
| Opaque -> Unseen
159+
| Stands_for_another -> Stands_for_another
160+
| Not_abstract -> (
161+
match (Ctype.expand_head_opt env ty).desc with
162+
| Tobject _ -> Unseen
163+
| _ -> Can_be_undefined)
146164

147165
let is_function_type env ty =
148166
match scrape env ty with

‎compiler/ml/typeopt.mli‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@ val maybe_pointer_type : Env.t -> Types.type_expr -> Lambda.immediate_or_pointer
2323

2424
val type_cannot_contain_undefined : Types.type_expr -> Env.t -> bool
2525

26+
(** Whether a type is an abstract type whose representation the compiler
27+
does not see, one that stands for another type (a functor parameter's or
28+
a locally abstract type), or neither *)
29+
type abstractness = Opaque | Stands_for_another | Not_abstract
30+
31+
val abstractness : Env.t -> Types.type_expr -> abstractness
32+
2633
(** Whether a type can hold [undefined]: it cannot, the compiler does not see
2734
its representation, it stands for another type (a functor parameter's or
2835
a locally abstract type), or it can *)

‎compiler/ml/variant_layout.ml‎

Lines changed: 6 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ let payload_kind ~env (t : Types.type_expr) : block_type option =
5757
annotated further down a chain of abbreviations. *)
5858
let declaration_shape ~env (decl : Types.type_declaration) : value_shape =
5959
match process_runtime_annotation decl.type_attributes with
60+
| None -> Unstated
6061
| Some (Type_of block_type) -> Recognized_as block_type
6162
| Some (Instance_of name) ->
6263
let ancestors =
@@ -68,13 +69,11 @@ let declaration_shape ~env (decl : Types.type_declaration) : value_shape =
6869
| Some _ | None -> []
6970
in
7071
Recognized_as (InstanceType (Class {name; ancestors}))
71-
| None -> (
72-
if not (has_not_undefined decl.type_attributes) then Unstated
73-
else
74-
(* Restating a kind the abbreviated type is recognized by keeps it *)
75-
match Option.map (value_shape ~env) decl.type_manifest with
76-
| Some (Recognized_as _ as shape) -> shape
77-
| Some (Unstated | Never_undefined) | None -> Never_undefined)
72+
| Some Not_undefined -> (
73+
(* Restating a kind the abbreviated type is recognized by keeps it *)
74+
match Option.map (value_shape ~env) decl.type_manifest with
75+
| Some (Recognized_as _ as shape) -> shape
76+
| Some (Unstated | Never_undefined) | None -> Never_undefined)
7877

7978
(* Resolves the shapes of a group of declarations, which can abbreviate each
8079
other. Each round resolves one more level of abbreviation within the
@@ -109,79 +108,6 @@ let resolve_shapes ~env (decls : (Ident.t * Types.type_declaration) list) =
109108
in
110109
round env decls (List.length decls)
111110

112-
(* Whether the abstract type at [path] has a representation of its own, which
113-
an annotation can refine, or stands for another type: a functor
114-
parameter's type, a recursive module's type being defined, or a locally
115-
abstract type. *)
116-
type abstractness = Opaque | Stands_for_another | Not_abstract
117-
118-
let abstractness ~env path =
119-
match Env.find_type path env with
120-
| {type_kind = Type_abstract; type_manifest = None; type_newtype_level} ->
121-
if type_newtype_level <> None || Env.is_functor_arg path env then
122-
Stands_for_another
123-
else if Predef.type_is_builtin_path_but_option path <> Predef.NA then
124-
Not_abstract
125-
else Opaque
126-
| _ -> Not_abstract
127-
| exception Not_found -> Not_abstract
128-
129-
let annotation_of_block_type = function
130-
| InstanceType (Class {name}) -> Instance_of name
131-
| block_type -> Type_of block_type
132-
133-
(* An annotation on an abbreviation is a claim about the abbreviated type, so
134-
it must agree with what the compiler knows about that type. It can refine
135-
an abstract type, restate the annotation the abbreviated type has, or, on a
136-
private abbreviation, declare a subclass of the class annotated there.
137-
Anything else, such as [@typeOf("string") type t = option<string>], would
138-
let two spellings of one type be recognized differently, and would make
139-
[Some(None)] of a type that can be undefined indistinguishable from
140-
[None]. *)
141-
let check_manifest_annotation ~loc ~env (decl : Types.type_declaration) =
142-
match
143-
(process_runtime_annotation decl.type_attributes, decl.type_manifest)
144-
with
145-
| None, _ | Some _, None -> ()
146-
| Some outer, Some manifest -> (
147-
let error err = raise (Error (loc, err)) in
148-
match (outer, payload_kind ~env manifest) with
149-
| _, None -> (
150-
match (Ctype.expand_head_opt env manifest).desc with
151-
| Tconstr (path, _, _) -> (
152-
match abstractness ~env path with
153-
| Opaque -> ()
154-
| Stands_for_another ->
155-
error
156-
(RuntimeAnnotationOnTypeParameter (runtime_attribute_name outer))
157-
| Not_abstract ->
158-
error
159-
(RuntimeAnnotationOnUnrelatedType (runtime_attribute_name outer)))
160-
| _ ->
161-
error (RuntimeAnnotationOnUnrelatedType (runtime_attribute_name outer)))
162-
| Type_of block_type, Some inner when block_type = inner -> ()
163-
| Instance_of name, Some (InstanceType (Class {name = inner}))
164-
when name = inner ->
165-
()
166-
| Instance_of name, Some ((InstanceType (Class _) | ObjectType) as inner) ->
167-
(* A public abbreviation would make every value of the superclass type
168-
a value of the subclass, without a coercion *)
169-
let superclass, ancestors =
170-
match inner with
171-
| InstanceType (Class {name = ancestor; ancestors}) ->
172-
(ancestor, ancestor :: ancestors)
173-
(* Every class instance is an object *)
174-
| _ -> ("Object", [])
175-
in
176-
if decl.type_private = Public then
177-
error (SubclassOfPublicAbbreviation (name, superclass))
178-
else if List.mem name ancestors then error (ClassTwiceInChain name)
179-
| (Instance_of _ | Type_of _), Some inner ->
180-
error
181-
(RuntimeAnnotationContradictsManifest
182-
( runtime_annotation_to_string outer,
183-
runtime_annotation_to_string (annotation_of_block_type inner) )))
184-
185111
let get_block_type ~env (cstr : Types.constructor_declaration) : block_type =
186112
match cstr.cd_args with
187113
| Cstr_tuple [ty] -> Option.value (payload_kind ~env ty) ~default:UnknownType

0 commit comments

Comments
 (0)