Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/instance-of-module.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `@module` beside `@instanceOf` now imports the class from that module, instead of being ignored. `@scope` on a type is an error: write the path in `@instanceOf`, such as `@instanceOf("THREE.Mesh")`.
17 changes: 1 addition & 16 deletions compiler/core/js_exp_make.ml
Original file line number Diff line number Diff line change
Expand Up @@ -1418,18 +1418,8 @@ let literal_tag = function
| Null -> nil
| Undefined -> undefined

(* The constructor of a class at a global path such as "Intl.Locale": a
global with properties, so that a binding that shadows the global's name
is noticed. *)
let class_constructor (instance : Variant_runtime.Instance.t) =
match
String.split_on_char '.' (Variant_runtime.Instance.to_string instance)
with
| [] -> assert false
| global :: properties -> List.fold_left dot (js_global global) properties

(* The [typeof] string an untagged payload answers to, as a [switch] key.
Instances are told apart by [is_instance_of], an unknown payload is not
Instances are told apart by their class, an unknown payload is not
checked *)
let block_type_name block_type =
match Variant_runtime.typeof_name block_type with
Expand All @@ -1440,11 +1430,6 @@ let tag_type = function
| Variant_runtime.Literal d -> literal_tag d
| Payload_shape b -> block_type_name b

let is_instance_of (instance : Variant_runtime.Instance.t) e =
match instance with
| Array -> is_array e
| Class _ -> instanceof e (class_constructor instance)

(* Whether a value of a tagged variant is a constant rather than a block,
given the literals of its constants *)
let is_int_tag ~(literal_tags : Variant_runtime.literal_tag list) e =
Expand Down
6 changes: 3 additions & 3 deletions compiler/core/js_exp_make.mli
Original file line number Diff line number Diff line change
Expand Up @@ -160,9 +160,6 @@ val assign : t -> t -> t
val literal_tag : Variant_runtime.literal_tag -> t
val tag_type : Variant_runtime.tag_type -> t

val is_instance_of : Variant_runtime.Instance.t -> t -> t
(** [Array.isArray(e)] or [e instanceof C] *)

val triple_equal : ?comment:string -> t -> t -> t
(* TODO: reduce [triple_equal] use *)

Expand All @@ -183,6 +180,9 @@ val is_type_object : t -> t
val typeof : t -> t
val is_array : t -> t

val instanceof : t -> t -> t
(** [e0 instanceof e1] *)

val to_int32 : t -> t

val int32_add : t -> t -> t
Expand Down
4 changes: 3 additions & 1 deletion compiler/core/lam_compile.ml
Original file line number Diff line number Diff line change
Expand Up @@ -970,7 +970,9 @@ let compile output_prefix =
match Variant_runtime.typeof_name block_type with
| Some name -> E.string_equal (E.typeof e) (E.str name)
| None -> assert false)
| Instance instance -> E.is_instance_of instance e
| Instance Array -> E.is_array e
| Instance (Class {name}) ->
E.instanceof e (Lam_compile_external_call.class_constructor name)
| Not_null -> E.not (E.is_null e)
| Not test -> E.not (test_exp test)
| And (test1, test2) -> E.and_ (test_exp test1) (test_exp test2)
Expand Down
16 changes: 16 additions & 0 deletions compiler/core/lam_compile_external_call.ml
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,22 @@ let translate_scoped_module_val
let start = E.js_global x in
Ext_list.fold_left (Ext_list.append_one rest fn) start E.dot)

(* The constructor of a class that values are recognized by: a global path
such as "Intl.Locale", read through the global so that a binding that
shadows its name is noticed, or an export of a module, imported as an
external's value would be *)
let class_constructor ({path; module_} : Variant_runtime.Instance.class_name) =
let module_name =
Option.map
(fun bundle : External_ffi_types.external_module_name ->
{bundle; module_bind_name = Phint_nothing; import_attributes = None})
module_
in
match List.rev (String.split_on_char '.' path) with
| [] -> assert false
| name :: scopes ->
translate_scoped_module_val module_name name (List.rev scopes)

(* The function a JSX external refers to; [Translcore] only builds [Pjsx]
for [Decl_val] externals that aren't the module itself *)
let jsx_callee
Expand Down
4 changes: 4 additions & 0 deletions compiler/core/lam_compile_external_call.mli
Original file line number Diff line number Diff line change
Expand Up @@ -57,5 +57,9 @@ val translate_ffi :
examples: "variadic"
*)

val class_constructor : Variant_runtime.Instance.class_name -> J.expression
(** The constructor of a class: its global, or its module's export, imported
as an external's value is *)

val jsx_callee : External_ffi_types.external_decl -> J.expression
(** The function a JSX external refers to, for [J.Jsx] *)
38 changes: 28 additions & 10 deletions compiler/ml/UntaggedVariants.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,9 @@ level implying the one before:
- `@typeOf("k")`: their `typeof` is `k`, one of `"string"`, `"number"`,
`"bigint"`, `"boolean"`, `"symbol"`, `"function"` and `"object"`;
- `@instanceOf("C")`: they are instances of the global class at the path `C`,
such as `"Date"` or `"Intl.Locale"`.
such as `"Date"` or `"Intl.Locale"`. With `@module("m")` beside it, `C` is
instead the path of an export of the module `m`, such as
`@module("three") @instanceOf("Mesh")`; `"default"` is its default export.

A type has at most one of the three, and only abstract types and type
abbreviations, public or private, can have one.
Expand Down Expand Up @@ -239,11 +241,27 @@ rejected as well:
| `String`, `Number`, `Boolean`, `BigInt`, `Symbol` | Values of type bigint are primitives ... | `instance_of_primitive_wrapper.res` |
| `globalThis`, `undefined`, `NaN`, `Infinity`, `Math`, `JSON`, `Reflect`, `Atomics`, `Intl`, `Proxy` | Math is not a class ... | `instance_of_not_a_class.res` |

An unknown `typeof` is an error too (`type_of_invalid.res`). The class is read
as a global; where a local binding of the same name is in scope, it is read
through `globalThis` (#8785). The compiler trusts the annotations, as it
trusts the type of an external: a value that is not what its type declares is
recognized by what it is (rule 10).
The path of a module's export may start with a keyword, such as `"default"`,
and is not checked against the globals above. A class is identified by its
path and its module: `Mesh` of `"three"` and the global `Mesh` are two classes
(`untagged_same_module_class_twice.res`,
`instance_of_module_interface_mismatch.res`). `@module` and `@scope` have no
other meaning on a type declaration:

| Declaration | Error | Fixture |
| --- | --- | --- |
| `@module("m")` without `@instanceOf` | @module on a type declaration names the module a class is imported from ... | `instance_of_module_without_class.res`, `instance_of_module_with_type_of.res` |
| `@module` without a module name | @module on a class expects the name of the module that exports it ... | `instance_of_module_without_name.res` |
| `@scope("A")` | @scope has no effect on a type declaration. Write the class's path in @instanceOf instead: @instanceOf("A.C"). | `instance_of_scope.res`, `instance_of_scope_without_class.res` |

An unknown `typeof` is an error too (`type_of_invalid.res`). A global class is
read as a global; where a local binding of the same name is in scope, it is
read through `globalThis` (#8785). A class of a module is imported where a
check needs it, as the value of a `@module` external is, and a relative module
path is written to the output as it is
(`tests/tests/src/untagged_module_classes_test.res`). The compiler trusts the
annotations, as it trusts the type of an external: a value that is not what
its type declares is recognized by what it is (rule 10).

The stdlib annotates the types of the classes it binds:

Expand Down Expand Up @@ -619,8 +637,8 @@ had to answer, and the answers of rule 5:
`undefined`.
8. **Abbreviations.** Annotations are read along the chain of abbreviations,
and a type is never recognized by its name.
9. **Globals.** A shadowed class is read through `globalThis`. A missing
class throws when the check runs (rule 10).
9. **Globals and imports.** A shadowed class is read through `globalThis`, a
class of a module is imported. A missing class throws when the check runs
(rule 10).

Still open: a class imported from a module cannot be named, and the typed
arrays share one type (#8955).
Still open: the typed arrays share one type (#8955).
94 changes: 78 additions & 16 deletions compiler/ml/ast_untagged_variants.ml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ type error =
| SubclassOfPublicAbbreviation of string * string
| ClassOnPublicAbbreviation of string
| ClassTwiceInChain of string
| InvalidClassModule
| ModuleWithoutInstanceOf
| ScopeOnType of string option
(** the [@instanceOf] path that says what the [@scope] meant *)
exception Error of Location.t * error

let report_error ppf =
Expand Down Expand Up @@ -107,7 +111,9 @@ let report_error ppf =
| InvalidInstanceOf ->
fprintf ppf
"@instanceOf expects the name of a global class, such as \
@instanceOf(\"Date\") or @instanceOf(\"Intl.Locale\")."
@instanceOf(\"Date\") or @instanceOf(\"Intl.Locale\"), or with @module \
the name of a class the module exports, such as @module(\"three\") \
@instanceOf(\"Mesh\")."
| UnsupportedInstanceOf (name, reason) -> (
match reason with
| Through_global_this ->
Expand Down Expand Up @@ -189,6 +195,22 @@ let report_error ppf =
"%s appears twice in this chain of abbreviations, so it would be its own \
superclass."
name
| InvalidClassModule ->
fprintf ppf
"@module on a class expects the name of the module that exports it, such \
as @module(\"three\") @instanceOf(\"Mesh\")."
| ModuleWithoutInstanceOf ->
fprintf ppf
"@module on a type declaration names the module a class is imported \
from, so it needs @instanceOf too, such as @module(\"three\") \
@instanceOf(\"Mesh\")."
| ScopeOnType None ->
fprintf ppf "@scope has no effect on a type declaration."
| ScopeOnType (Some path) ->
fprintf ppf
"@scope has no effect on a type declaration. Write the class's path in \
@instanceOf instead: @instanceOf(\"%s\")."
path

(*
Type of the runtime representation of a tag.
Expand Down Expand Up @@ -259,7 +281,7 @@ let report_constructor_more_than_one_arg ~loc ~name =
states about the runtime representation of its values. *)
type runtime_annotation =
| Not_undefined (** values that are never [undefined] *)
| Instance_of of string (** instances of the global class at this path *)
| Instance_of of Instance.class_name (** instances of this class *)
| Type_of of block_type (** values with this [typeof] *)

let not_undefined = "notUndefined"
Expand Down Expand Up @@ -288,7 +310,10 @@ let unsupported_class name =
| _ -> None)
| _ -> None

let is_class_path name =
(* A path of identifiers. The first one names a global, which may not be a
keyword, or with [~exported] an export of a module, which may: a module's
default export is ["default"]. *)
let is_class_path ~exported name =
let is_start = function
| 'A' .. 'Z' | 'a' .. 'z' | '_' | '$' -> true
| _ -> false
Expand All @@ -304,7 +329,7 @@ let is_class_path name =
| global :: properties ->
(* Properties may be named like keywords, the global may not *)
is_identifier global
&& (not (Js_reserved_map.is_js_keyword global))
&& (exported || not (Js_reserved_map.is_js_keyword global))
&& List.for_all is_identifier properties
| [] -> false

Expand All @@ -319,17 +344,23 @@ let typeof_name block_type =

let runtime_annotation_to_string = function
| Not_undefined -> "@" ^ not_undefined
| Instance_of name -> Printf.sprintf "@%s(\"%s\")" instance_of name
| Instance_of {path; module_ = None} ->
Printf.sprintf "@%s(\"%s\")" instance_of path
| Instance_of {path; module_ = Some module_} ->
Printf.sprintf "@module(\"%s\") @%s(\"%s\")" module_ instance_of path
| Type_of block_type ->
Printf.sprintf "@%s(\"%s\")" type_of (typeof_name block_type)

(* What a declaration's annotations state about its values, for error
messages *)
let describe_declared_values = function
| Some (InstanceType (Class {name; ancestors = []})) -> "instances of " ^ name
| Some (InstanceType (Class {name; ancestors = []})) ->
"instances of " ^ Instance.class_name_to_string name
| Some (InstanceType (Class {name; ancestors})) ->
"instances of " ^ name ^ ", a subclass of "
^ String.concat " and " ancestors
"instances of "
^ Instance.class_name_to_string name
^ ", a subclass of "
^ String.concat " and " (List.map Instance.class_name_to_string ancestors)
| Some (InstanceType Array) -> "arrays"
| Some block_type -> "typeof \"" ^ typeof_name block_type ^ "\""
| None -> "no stated class or typeof"
Expand All @@ -339,16 +370,30 @@ let describe_declared_values = function
accepted. *)
let process_runtime_annotation ?(loc = Location.none)
(attrs : Parsetree.attributes) =
let annotation_of ({Location.txt; loc = attr_loc}, payload) =
let loc = if attr_loc = Location.none then loc else attr_loc in
let attr_loc attr_loc = if attr_loc = Location.none then loc else attr_loc in
(* The module a class is imported from: [@module] beside [@instanceOf] *)
let class_module () =
List.find_map
(fun ({Location.txt; loc}, payload) ->
if txt = "module" then
match Ast_payload.semantic_string_of_payload payload with
| Some module_ when module_ <> "" -> Some module_
| _ -> raise (Error (attr_loc loc, InvalidClassModule))
else None)
attrs
in
let annotation_of ({Location.txt; loc}, payload) =
let loc = attr_loc loc in
if txt = not_undefined then Some Not_undefined
else if txt = instance_of then
let module_ = class_module () in
match Ast_payload.semantic_string_of_payload payload with
| Some name when is_class_path name -> (
match unsupported_class name with
| None -> Some (Instance_of name)
| Some reason ->
raise (Error (loc, UnsupportedInstanceOf (name, reason))))
| Some path when is_class_path ~exported:(module_ <> None) path -> (
(* A module's export can be named like a global without being it *)
match (module_, unsupported_class path) with
| None, Some reason ->
raise (Error (loc, UnsupportedInstanceOf (path, reason)))
| Some _, _ | None, None -> Some (Instance_of {path; module_}))
| _ -> raise (Error (loc, InvalidInstanceOf))
else if txt = type_of then
match Ast_payload.semantic_string_of_payload payload with
Expand All @@ -374,7 +419,24 @@ let process_runtime_annotation ?(loc = Location.none)
[is_abstract_or_abbreviation]. *)
let check_runtime_annotation ~loc ~is_abstract_or_abbreviation
(attrs : Parsetree.attributes) =
match process_runtime_annotation ~loc attrs with
let annotation = process_runtime_annotation ~loc attrs in
(* [@module] and [@scope] are read on a type declaration only as the place
of a class; anywhere else they would be silently ignored *)
Ext_list.iter attrs (fun ({Location.txt; loc}, payload) ->
match (txt, annotation) with
| "module", Some (Instance_of _) -> ()
| "module", _ -> raise (Error (loc, ModuleWithoutInstanceOf))
| "scope", Some (Instance_of {path}) ->
(* [@scope("THREE")] meant the class at [THREE.Mesh] *)
let meant =
Option.map
(fun scope -> scope ^ "." ^ path)
(Ast_payload.semantic_string_of_payload payload)
in
raise (Error (loc, ScopeOnType meant))
| "scope", _ -> raise (Error (loc, ScopeOnType None))
| _ -> ());
match annotation with
| None -> ()
| Some annotation ->
if not is_abstract_or_abbreviation then
Expand Down
4 changes: 3 additions & 1 deletion compiler/ml/predef.ml
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,9 @@ let common_initial_env add_type add_extension empty_env =
type_arity = 1;
type_variance = [Variance.covariant];
type_shape =
Recognized_as (InstanceType (Class {name = "Promise"; ancestors = []}));
Recognized_as
(InstanceType
(Class {name = {path = "Promise"; module_ = None}; ancestors = []}));
}
and decl_tagged_template =
let tvar1, tvar2 = (newgenvar (), newgenvar ()) in
Expand Down
11 changes: 6 additions & 5 deletions compiler/ml/typedecl.ml
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,7 @@ let check_manifest_annotation ~loc ~env (decl : Types.type_declaration) =
them apart *)
match outer with
| Instance_of name when decl.type_private = Public ->
error (ClassOnPublicAbbreviation name)
error (ClassOnPublicAbbreviation (Instance.class_name_to_string name))
| Not_undefined | Instance_of _ | Type_of _ -> ())
| Stands_for_another -> stands_for_another ()
| Not_abstract -> unrelated ())
Expand All @@ -387,15 +387,16 @@ let check_manifest_annotation ~loc ~env (decl : Types.type_declaration) =
let superclass, ancestors =
match inner with
| InstanceType (Class {name = ancestor; ancestors}) ->
(ancestor, ancestor :: ancestors)
(Instance.class_name_to_string ancestor, ancestor :: ancestors)
(* Every class instance is an object *)
| _ -> ("Object", [])
in
let name_string = Instance.class_name_to_string name in
if decl.type_private = Public then
error (SubclassOfPublicAbbreviation (name, superclass))
else if List.mem name ancestors then error (ClassTwiceInChain name)
error (SubclassOfPublicAbbreviation (name_string, superclass))
else if List.mem name ancestors then error (ClassTwiceInChain name_string)
| Instance_of name, Some (InstanceType Array) ->
error (SubclassOfArray name)
error (SubclassOfArray (Instance.class_name_to_string name))
| (Instance_of _ | Type_of _), Some inner ->
let recognized_by =
match inner with
Expand Down
11 changes: 9 additions & 2 deletions compiler/ml/variant_runtime.ml
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,18 @@
each declaration. *)

module Instance = struct
type t = Array | Class of {name: string; ancestors: string list}
type class_name = {path: string; module_: string option}

type t = Array | Class of {name: class_name; ancestors: class_name list}

let class_name_to_string {path; module_} =
match module_ with
| None -> path
| Some module_ -> Printf.sprintf "%s from \"%s\"" path module_

let to_string = function
| Array -> "Array"
| Class {name} -> name
| Class {name} -> class_name_to_string name

let is_subclass t ~of_ =
match (t, of_) with
Expand Down
Loading
Loading