Skip to content

Commit fa730fd

Browse files
cknittclaude
andcommitted
Check runtime annotations against the types they describe
Why: An annotation on an abbreviation was trusted whatever the abbreviated type was. `@typeOf("string") type s = option<string>` made `Some(None)` of `s` the same value as `None`, and two spellings of one type were recognized differently. Paths such as `Object`, `BigInt` or `globalThis.Date` were accepted and misrecognized every value or duplicated another class. An annotation on an abbreviation must now refine an abstract type that is not builtin, repeat the abbreviated type's annotation, or declare a subclass of the class annotated there. A subclass needs a private abbreviation, or a public one that is a strict instance of the superclass type (a phantom type hierarchy), and must not repeat a class of its chain. Paths that name no class to recognize values by are rejected. Payloads of `@unboxed` wrappers of annotated types are never undefined either, as with `@notUndefined`, and the function check excludes class cases as the object check does, so the two-arm form agrees with the `switch` form. Diagnostic added (annotation on a type that can be undefined): Example: @typeof("string") type s = option<string> After (diagnostic): @typeof on a type abbreviation must describe an abstract type, or a type with the same annotation. The abbreviated type already has a runtime representation the compiler knows, or can be undefined. Diagnostic added (subclass on a public abbreviation): Example: @instanceof("Animal") type animal @instanceof("Dog") type dog = animal After (diagnostic): A subclass must be a private abbreviation: write `= private ...` so that instances of Animal cannot be used as instances of Dog without a coercion. Diagnostic added (class path): Example: @instanceof("BigInt") type t After (diagnostic): Values of type bigint are primitives, not instances of BigInt. Use @typeof("bigint") instead. JS modified (option of an unboxed wrapper): Example: @unboxed type boxedAnimal = BoxedAnimal(animal) let x: option<boxedAnimal> = Some(BoxedAnimal(a)) Before (js): let x = Primitive_option.some(a); After (js): let x = a; JS modified (function case beside a class case): Example: @unboxed type handler = Function(int => int) | Callable(callable) Before (js): if (typeof handler === "function") { return "function"; } After (js): if (typeof handler === "function" && !(handler instanceof UntaggedCallable)) { return "function"; } Review: Why allow public subclasses that are strict instances? `Dom.res` and WebAPI model class hierarchies with phantom types, such as `type element<'a> = node<_element<'a>>`, whose subclass types unify with the superclass type only at the phantom argument. `type dog = animal` is the same type as `animal` and is rejected. Review: Why reject `globalThis.C` instead of normalizing it? The compiler already reads a shadowed class through `globalThis`, so the prefix adds nothing, and one spelling per class keeps the duplicate and subclass checks, which compare paths, exact. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Fc7LEuyEfynjaKCVEBPmTF Signed-off-by: Christoph Knittel <ck@cca.io>
1 parent 1a63e96 commit fa730fd

26 files changed

Lines changed: 373 additions & 38 deletions

‎compiler/ml/ast_untagged_variants.ml‎

Lines changed: 115 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,15 @@ type untagged_error =
1313
| UnreachableBoolean of string
1414
| DuplicateLiteral of string
1515
| ConstructorMoreThanOneArg of string
16+
17+
(* Why a syntactically valid [@instanceOf] path is still not accepted *)
18+
and unsupported_class =
19+
| Through_global_this
20+
| Every_value_of of string (** names the [@typeOf] that says the same *)
21+
| Wrapper_of of string (** names the [@typeOf] of the wrapped primitive *)
22+
| Array_class
23+
| Not_a_class
24+
1625
type error =
1726
| InvalidVariantAsAnnotation
1827
| VariantAsIntegerOutOfRange of string
@@ -21,9 +30,14 @@ type error =
2130
| InvalidUntaggedVariantDefinition of untagged_error
2231
| TagFieldNameConflict of string * string * string
2332
| InvalidInstanceOf
33+
| UnsupportedInstanceOf of string * unsupported_class
2434
| InvalidTypeOf of string
2535
| ConflictingRuntimeAnnotations
2636
| RuntimeAnnotationOnRepresentedType of string
37+
| RuntimeAnnotationOnUnrelatedType of string
38+
| RuntimeAnnotationContradictsManifest of string * string
39+
| SubclassOfPublicAbbreviation of string * string
40+
| ClassTwiceInChain of string
2741
exception Error of Location.t * error
2842

2943
let report_error ppf =
@@ -77,6 +91,30 @@ let report_error ppf =
7791
fprintf ppf
7892
"@instanceOf expects the name of a global class, such as \
7993
@instanceOf(\"Date\") or @instanceOf(\"Intl.Locale\")."
94+
| UnsupportedInstanceOf (name, reason) -> (
95+
match reason with
96+
| Through_global_this ->
97+
fprintf ppf
98+
"Write @instanceOf(\"%s\") without \"globalThis.\": the compiler reads \
99+
the class through globalThis itself where a local binding shadows it."
100+
(String.concat "." (List.tl (String.split_on_char '.' name)))
101+
| Every_value_of type_of ->
102+
fprintf ppf
103+
"Every %s is an instance of %s, so @instanceOf(\"%s\") cannot tell \
104+
cases apart. Use @typeOf(\"%s\") instead."
105+
type_of name name type_of
106+
| Wrapper_of type_of ->
107+
fprintf ppf
108+
"Values of type %s are primitives, not instances of %s. Use \
109+
@typeOf(\"%s\") instead."
110+
type_of name type_of
111+
| Array_class ->
112+
fprintf ppf
113+
"Arrays are recognized by Array.isArray. Use array<_> as the payload \
114+
type instead of @instanceOf(\"Array\")."
115+
| Not_a_class ->
116+
fprintf ppf "%s is not a class, so it cannot be used with @instanceOf."
117+
name)
80118
| InvalidTypeOf name ->
81119
fprintf ppf
82120
"@typeOf expects one of \"string\", \"number\", \"bigint\", \"boolean\", \
@@ -89,6 +127,27 @@ let report_error ppf =
89127
"@%s can only be used on abstract types and type abbreviations, whose \
90128
runtime representation it describes."
91129
attribute
130+
| RuntimeAnnotationOnUnrelatedType attribute ->
131+
fprintf ppf
132+
"@%s on a type abbreviation must describe an abstract type, or a type \
133+
with the same annotation. The abbreviated type already has a runtime \
134+
representation the compiler knows, or can be undefined."
135+
attribute
136+
| RuntimeAnnotationContradictsManifest (outer, inner) ->
137+
fprintf ppf
138+
"This annotation, %s, contradicts the abbreviated type's annotation, %s."
139+
outer inner
140+
| SubclassOfPublicAbbreviation (name, ancestor) ->
141+
fprintf ppf
142+
"A subclass must be a private abbreviation: write `= private ...` so \
143+
that instances of %s cannot be used as instances of %s without a \
144+
coercion."
145+
ancestor name
146+
| ClassTwiceInChain name ->
147+
fprintf ppf
148+
"%s appears twice in this chain of abbreviations, so it would be its own \
149+
superclass."
150+
name
92151

93152
(*
94153
Type of the runtime representation of a tag.
@@ -178,6 +237,28 @@ type runtime_annotation =
178237
let instance_of = "instanceOf"
179238
let type_of = "typeOf"
180239

240+
(* The reason a global that is a valid path is still not a class to recognize
241+
values by. Classes nested in namespaces, such as [Intl.Locale], are not
242+
checked. *)
243+
let unsupported_class name =
244+
match String.split_on_char '.' name with
245+
| "globalThis" :: _ :: _ -> Some Through_global_this
246+
| [global] -> (
247+
match global with
248+
| "Object" -> Some (Every_value_of "object")
249+
| "Function" -> Some (Every_value_of "function")
250+
| "Array" -> Some Array_class
251+
| "String" -> Some (Wrapper_of "string")
252+
| "Number" -> Some (Wrapper_of "number")
253+
| "Boolean" -> Some (Wrapper_of "boolean")
254+
| "BigInt" -> Some (Wrapper_of "bigint")
255+
| "Symbol" -> Some (Wrapper_of "symbol")
256+
| "globalThis" | "undefined" | "NaN" | "Infinity" | "Math" | "JSON"
257+
| "Reflect" | "Atomics" | "Intl" | "Proxy" ->
258+
Some Not_a_class
259+
| _ -> None)
260+
| _ -> None
261+
181262
let is_class_path name =
182263
let is_start = function
183264
| 'A' .. 'Z' | 'a' .. 'z' | '_' | '$' -> true
@@ -208,6 +289,24 @@ let block_type_of_typeof = function
208289
| "object" -> Some ObjectType
209290
| _ -> None
210291

292+
let runtime_attribute_name = function
293+
| Instance_of _ -> instance_of
294+
| Type_of _ -> type_of
295+
296+
let typeof_name = function
297+
| StringType -> "string"
298+
| IntType | FloatType -> "number"
299+
| BigintType -> "bigint"
300+
| BooleanType -> "boolean"
301+
| SymbolType -> "symbol"
302+
| FunctionType -> "function"
303+
| ObjectType | InstanceType _ | UnknownType -> "object"
304+
305+
let runtime_annotation_to_string = function
306+
| Instance_of name -> Printf.sprintf "@%s(\"%s\")" instance_of name
307+
| Type_of block_type ->
308+
Printf.sprintf "@%s(\"%s\")" type_of (typeof_name block_type)
309+
211310
(* The [@instanceOf] or [@typeOf] annotation in [attrs], validated. Only
212311
[Typedecl] passes [~loc]; later readers see attributes it accepted. *)
213312
let process_runtime_annotation ?(loc = Location.none)
@@ -216,7 +315,11 @@ let process_runtime_annotation ?(loc = Location.none)
216315
let loc = if attr_loc = Location.none then loc else attr_loc in
217316
if txt = instance_of then
218317
match Ast_payload.semantic_string_of_payload payload with
219-
| Some name when is_class_path name -> Some (Instance_of name)
318+
| Some name when is_class_path name -> (
319+
match unsupported_class name with
320+
| None -> Some (Instance_of name)
321+
| Some reason ->
322+
raise (Error (loc, UnsupportedInstanceOf (name, reason))))
220323
| _ -> raise (Error (loc, InvalidInstanceOf))
221324
else if txt = type_of then
222325
match Ast_payload.semantic_string_of_payload payload with
@@ -244,9 +347,7 @@ let check_runtime_annotation ~loc ~is_abstract_or_abbreviation
244347
(Error
245348
( loc,
246349
RuntimeAnnotationOnRepresentedType
247-
(match annotation with
248-
| Instance_of _ -> instance_of
249-
| Type_of _ -> type_of) ))
350+
(runtime_attribute_name annotation) ))
250351

251352
let type_is_builtin_object (t : Types.type_expr) =
252353
match t.desc with
@@ -630,22 +731,21 @@ module Dynamic_checks = struct
630731
| InstanceType i -> Some i
631732
| _ -> None)
632733
in
734+
(* Instances of a class can be objects or functions, so the cases of
735+
those kinds exclude the class cases *)
736+
let not_one_of_the_instances case =
737+
Ext_list.fold_right instances case (fun i x ->
738+
x &&& not (is_instance i y))
739+
in
633740
match tag_type with
634741
| Payload_shape
635742
( IntType | StringType | FloatType | BigintType | BooleanType
636-
| SymbolType | FunctionType ) ->
743+
| SymbolType ) ->
637744
typeof y == x
745+
| Payload_shape FunctionType -> not_one_of_the_instances (typeof y == x)
638746
| Payload_shape ObjectType ->
639-
let object_case =
640-
if has_null_case then typeof y == x &&& (y != nil) else typeof y == x
641-
in
642-
if instances <> [] then
643-
let not_one_of_the_instances =
644-
Ext_list.fold_right instances object_case (fun i x ->
645-
x &&& not (is_instance i y))
646-
in
647-
not_one_of_the_instances
648-
else object_case
747+
not_one_of_the_instances
748+
(if has_null_case then typeof y == x &&& (y != nil) else typeof y == x)
649749
| Payload_shape (InstanceType i) -> is_case_instance ~instances i y
650750
| Payload_shape UnknownType ->
651751
(* This should not happen because unknown must be the only non-literal case *)

‎compiler/ml/typedecl.ml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1612,6 +1612,11 @@ let transl_type_decl env rec_flag sdecl_list =
16121612
| Type_abstract | Type_record _ | Type_open -> (id, decl))
16131613
decls
16141614
in
1615+
List.iter2
1616+
(fun sdecl (_, decl) ->
1617+
Variant_layout.check_manifest_annotation ~loc:sdecl.ptype_loc ~env:newenv
1618+
decl)
1619+
sdecl_list decls;
16151620
List.iter2 (check_constraints ~type_record_as_object newenv) sdecl_list decls;
16161621
(* Name recursion *)
16171622
let decls =
@@ -2019,6 +2024,7 @@ let transl_with_constraint env id row_path orig_decl sdecl =
20192024
(match Ctype.closed_type_decl decl with
20202025
| None -> ()
20212026
| Some ty -> raise (Error (sdecl.ptype_loc, Unbound_type_var (ty, decl))));
2027+
Variant_layout.check_manifest_annotation ~loc:sdecl.ptype_loc ~env decl;
20222028
let decl = name_recursion sdecl id decl in
20232029
let type_variance =
20242030
compute_variance_decl env true decl

‎compiler/ml/typeopt.ml‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,14 @@ let scrape env ty = (scrape_ty env ty).desc
3939
*)
4040
let rec type_cannot_contain_undefined (typ : Types.type_expr) (env : Env.t) =
4141
(* A value declared to be a class instance or to have a [typeof] other than
42-
"undefined" is not undefined *)
42+
"undefined" is not undefined. The payload of an [@unboxed] wrapper is
43+
declared only after scraping. *)
4344
Option.is_some (Variant_layout.declared_block_type ~env typ)
4445
||
45-
match scrape env typ with
46+
let scraped = scrape_ty env typ in
47+
Option.is_some (Variant_layout.declared_block_type ~env scraped)
48+
||
49+
match scraped.desc with
4650
| Tconstr (p, _, _) -> (
4751
(* all built in types could not inhabit none-like values:
4852
int, char, float, bool, unit, exn, array, list, nativeint,

‎compiler/ml/variant_layout.ml‎

Lines changed: 56 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,9 @@ let runtime_annotations ~env (t : Types.type_expr) =
4040
in
4141
collect ~previous:None t
4242

43-
(* The block type the outermost annotation of [t] states. A class's
44-
ancestors are the classes annotated further down the chain. *)
45-
let declared_block_type ~env t =
46-
match runtime_annotations ~env t with
43+
(* The block type the outermost of [annotations] states. A class's ancestors
44+
are the classes annotated further down the chain. *)
45+
let block_type_of_annotations = function
4746
| Instance_of name :: rest ->
4847
let ancestors =
4948
List.filter_map
@@ -56,6 +55,59 @@ let declared_block_type ~env t =
5655
| Type_of block_type :: _ -> Some block_type
5756
| [] -> None
5857

58+
let declared_block_type ~env t =
59+
block_type_of_annotations (runtime_annotations ~env t)
60+
61+
(* An annotation on an abbreviation is a claim about the abbreviated type, so
62+
it must agree with what the compiler knows about that type. It can refine
63+
an abstract type, restate the annotation the abbreviated type has, or, on a
64+
private abbreviation, declare a subclass of the class annotated there.
65+
Anything else, such as [@typeOf("string") type t = option<string>], would
66+
let two spellings of one type be recognized differently, and would make
67+
[Some(None)] of a type that can be undefined indistinguishable from
68+
[None]. *)
69+
let check_manifest_annotation ~loc ~env (decl : Types.type_declaration) =
70+
match
71+
(process_runtime_annotation decl.type_attributes, decl.type_manifest)
72+
with
73+
| None, _ | Some _, None -> ()
74+
| Some outer, Some manifest -> (
75+
let error err = raise (Error (loc, err)) in
76+
match (outer, runtime_annotations ~env manifest) with
77+
| _, [] -> (
78+
let is_abstract path =
79+
match Env.find_type path env with
80+
| {type_kind = Type_abstract; type_manifest = None} -> true
81+
| _ -> false
82+
| exception Not_found -> false
83+
in
84+
match (Ctype.expand_head_opt env manifest).desc with
85+
| Tconstr (path, _, _)
86+
when Predef.type_is_builtin_path_but_option path = Predef.NA
87+
&& is_abstract path ->
88+
()
89+
| _ ->
90+
error (RuntimeAnnotationOnUnrelatedType (runtime_attribute_name outer)))
91+
| Type_of block_type, Type_of inner :: _ when block_type = inner -> ()
92+
| Instance_of name, Instance_of inner :: _ when name = inner -> ()
93+
| Instance_of name, (Instance_of ancestor :: _ as chain) ->
94+
(* A public abbreviation is the same type as the superclass, unless it
95+
is a strict instance of it, as in the phantom type hierarchy
96+
[type element<'a> = node<_element<'a>>] *)
97+
let same_type =
98+
match (Btype.repr manifest).desc with
99+
| Tconstr (_, args, _) -> List.for_all Btype.is_Tvar args
100+
| _ -> true
101+
in
102+
if decl.type_private = Public && same_type then
103+
error (SubclassOfPublicAbbreviation (name, ancestor))
104+
else if List.mem outer chain then error (ClassTwiceInChain name)
105+
| (Instance_of _ | Type_of _), inner :: _ ->
106+
error
107+
(RuntimeAnnotationContradictsManifest
108+
( runtime_annotation_to_string outer,
109+
runtime_annotation_to_string inner )))
110+
59111
let get_block_type_from_typ ~env (t : Types.type_expr) : block_type option =
60112
match declared_block_type ~env t with
61113
| Some _ as declared -> declared
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
We've found a bug for you!
3+
/.../fixtures/instance_of_array.res:1:1-11
4+
5+
1 │ @instanceOf("Array") type t
6+
2 │
7+
8+
Arrays are recognized by Array.isArray. Use array<_> as the payload type instead of @instanceOf("Array").
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
2+
We've found a bug for you!
3+
/.../fixtures/instance_of_class_twice_in_chain.res:3:23-42
4+
5+
1 │ @instanceOf("Animal") type animal
6+
2 │ @instanceOf("Dog") type dog = private animal
7+
3 │ @instanceOf("Animal") type t = private dog
8+
4 │
9+
10+
Animal appears twice in this chain of abbreviations, so it would be its own superclass.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
We've found a bug for you!
3+
/.../fixtures/instance_of_global_this.res:1:1-11
4+
5+
1 │ @instanceOf("globalThis.Date") type t
6+
2 │
7+
8+
Write @instanceOf("Date") without "globalThis.": the compiler reads the class through globalThis itself where a local binding shadows it.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
We've found a bug for you!
3+
/.../fixtures/instance_of_not_a_class.res:1:1-11
4+
5+
1 │ @instanceOf("Math") type t
6+
2 │
7+
8+
Math is not a class, so it cannot be used with @instanceOf.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
We've found a bug for you!
3+
/.../fixtures/instance_of_object.res:1:1-11
4+
5+
1 │ @instanceOf("Object") type t
6+
2 │
7+
8+
Every object is an instance of Object, so @instanceOf("Object") cannot tell cases apart. Use @typeOf("object") instead.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
We've found a bug for you!
3+
/.../fixtures/instance_of_primitive_wrapper.res:1:1-11
4+
5+
1 │ @instanceOf("BigInt") type t
6+
2 │
7+
8+
Values of type bigint are primitives, not instances of BigInt. Use @typeOf("bigint") instead.

0 commit comments

Comments
 (0)