From 4114973075d669578817dc58719f1600c4c11ae1 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 10 Nov 2026 19:24:55 +0000 Subject: [PATCH] Resolve an external's FFI attributes in the type checker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: The parsetree is what PPXs see and what `-bs-ast` serializes, and #8624 wants it to describe source only. After the built-in PPX had read an external's `@send`, `@module`, `@as`… attributes, it replaced the primitive string with the computed FFI specification (`Prim_ffi`, `Prim_inline_const`), so `Parsetree` depended on `External_ffi_types` and carried cases no PPX can observe. Now `pval_prim` is the string as written (`string option`), and `Typedecl` resolves the attributes through `Primitive.resolve_external`, a hook the frontend registers since the resolver lives above `compiler/ml`. The frontend no longer resolves them as well. The resolver also reports the external's errors and warnings, inside the declaration's `@warning` scope, and after any `@@warning` above it in the file. The generated JavaScript is unchanged. AST modified (externals after the built-in PPX): Example: type t @send external on: (t, @as("click") _, unit => unit) => unit = "addEventListener" @inline let answer = 42 Before (expanded): … structure_item Pstr_primitive value_description "on" core_type Ptyp_arrow arity = 2 Nolabel core_type Ptyp_constr "t" [] Nolabel core_type Ptyp_arrow … core_type Ptyp_constr "unit" [] "addEventListener" structure_item Pstr_primitive value_description "answer" core_type Ptyp_constr "int" [] After (expanded): … structure_item Pstr_primitive value_description "on" attribute "send" [] core_type Ptyp_arrow arity = 3 Nolabel core_type Ptyp_constr "t" [] Nolabel Parg_fixed value Pfixed_string (source="click", semantic="click") Nolabel core_type Ptyp_arrow … core_type Ptyp_constr "unit" [] "addEventListener" structure_item Pstr_primitive value_description "answer" attribute "inline" [ structure_item Pstr_eval expression Pexp_constant PConst_int (42,None) ] core_type Ptyp_constr "int" [] "#rescript-inline" AST modified (an external with a relative path after the built-in PPX): Example: @module("./local") external relative: int => int = "relative" Before (expanded): structure_item Pstr_include module_expr Pmod_constraint module_expr Pmod_structure [ structure_item Pstr_primitive value_description "relative" attribute "module" … core_type … "relative" ] module_type Pmty_signature [ signature_item Psig_value value_description "relative" core_type … ] After (expanded): structure_item Pstr_primitive value_description "relative" attribute "module" … core_type … "relative" Typedtree modified (an external with a relative path): Example: @module("./local") external relative: int => int = "relative" Before (typed): the constraint the built-in PPX wrote structure_item Tstr_include module_expr Tmod_constraint module_expr Tmod_structure [ structure_item Tstr_primitive value_description relative/1001 … "relative" ] module_type Tmty_signature [ signature_item Tsig_value value_description relative/1002 … ] After (typed): the constraint Typemod adds, implicit structure_item Tstr_include module_expr module_expr Tmod_structure [ structure_item Tstr_primitive value_description relative/1001 … "relative" ] Typedtree modified (externals): Example: type t @send external on: (t, @as("click") _, unit => unit) => unit = "addEventListener" @inline let answer = 42 Before (typed): … structure_item Tstr_primitive value_description on/1002 core_type Ttyp_arrow … "addEventListener" structure_item Tstr_primitive value_description answer/1003 core_type Ttyp_constr "int/1" [] After (typed): … structure_item Tstr_primitive value_description on/1002 core_type Ttyp_arrow … "addEventListener" structure_item Tstr_primitive value_description answer/1003 core_type Ttyp_constr "int/1" [] "#rescript-inline" Diagnostic modified (unused attribute on a relative @module external): Example: @module("./local") external relative: @as("v") int => unit = "relative" Before (diagnostic): Warning number 101 A.res:1:39-41 Unused attribute: @as Warning number 101 A.res:1:39-41 Unused attribute: @as After (diagnostic): Warning number 101 A.res:1:39-41 Unused attribute: @as Diagnostic removed (unused attribute under a @warning that disables it): Example: @warning("-101") @module("./local") external silenced: @as("w") int => unit = "silenced" Before (diagnostic): Warning number 101 A.res:2:21-23 Unused attribute: @as Diagnostic removed (unused attribute after a @@warning that disables it): Example: @send external first: (string, @as("x") int) => unit = "first" @@warning("-101") @send external second: (string, @as("y") int) => unit = "second" Before (diagnostic): Warning number 101 A.res:1:32-34 Unused attribute: @as Warning number 101 A.res:3:33-35 Unused attribute: @as After (diagnostic): Warning number 101 A.res:1:32-34 Unused attribute: @as Diagnostic added (an external that names the inline-constant primitive): Example: external answer: int = "#rescript-inline" After (diagnostic): "#rescript-inline" is reserved for @inline constants JS modified (@inline let with a bigint): Example: @inline let big = 10n let use = () => big Before (js): function use() { return 10n; } let big = 10n; exports.big = big; exports.use = use; After (js): function use() { return 10n; } exports.use = use; Diagnostic removed (@inline on a bigint let): Example: @inline let big = 10n Before (diagnostic): Warning number 53 the @inline attribute cannot appear in this context Review: How does an external with a relative path stay out of other modules? Its path is relative to the file that declares it, so other modules call the value its module exports. In a signature, `Typedecl` gives it `Val_reg`. In a structure, `Typemod` types it as `include (struct external … end : {let …})`, the wrapper the built-in PPX used to write, whose coercion (`Tcoerce_primitive`) emits the exported function. `Primitive.no_cross_module_inline` reads relativeness off the resolved spec (`External_ffi_types.is_relative`, split out of `check_decl`). Review: Why a hook rather than passing the result along? `-bs-ast` writes the parsetree after the built-in PPX and a later `bsc` process reads it back, so the specification has to be recomputable from the tree. `Ppx_entry`, which every compiler driver links, registers the resolver at module initialization, as the `Oprint` hooks are. Review: What do diagnostics look like now? An external's errors and warning 101 come during type checking, in source order with the type errors, instead of in the parse step; an earlier type error hides them until it is fixed. The reprint path and `-bs-ast` alone no longer report them. Review: Is each external resolved once? Yes, except in a recursive module's signature, which the type checker types twice, the first time with warnings off, so its diagnostics come once. Review: What does this cost? Each external is resolved in the compile step, which reads it as written, attributes and all. The unused-attribute walk on the resolved form is skipped unless it checks one of the attributes, which is the common case. Parse and compile steps together allocate 0.65% fewer words than before on Stdlib_Math.resi, 0.39% more on Stdlib_Math.res, and 1.4% more on Stdlib_Symbol.res, a small file of `@val @scope(...)` constants. Review: What is `"#rescript-inline"`? The primitive of an `@inline` constant's declaration, which keeps its `@inline()` attribute; the resolver turns it into `Kind_inline_const`. A structural form is a separate #8624 item. Review: Do PPXs see a difference? No: they run before the built-in PPX, and the v0 bridge carries the string as before; its error branch for already-resolved externals is gone. Review: What changes under `-bs-no-builtin-ppx`? An external with a plain name is now resolved as an FFI external by the type checker; before, it was typed as an intrinsic of that name. Review: What else goes? `Typedtree.val_prim`, a copy of the primitive string whose readers only need the value's resolved kind, and `Primitive.print`: `Outcometree.oval_prim` is the `Primitive.description` itself. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_018oLiCQjGFSE2qwfYqCMF9e Claude-Session: https://claude.ai/code/session_01Kbf3gLpf7RN1MiRcubPgRn Claude-Session: https://claude.ai/code/session_01Kbf3gJFAva9685fjvkajub Claude-Session: https://claude.ai/code/session_01Kbf3gGqcYiyMeZgs8UzT5G Signed-off-by: Christoph Knittel --- changes/external-unused-attribute-once.fix.md | 1 + changes/external-warning-attribute.fix.md | 1 + changes/inline-bigint-let.fix.md | 1 + changes/resolve-ffi-externals.internal.md | 1 + compiler/core/lam_compile_external_call.ml | 2 +- compiler/frontend/ast_attributes.ml | 15 +- compiler/frontend/ast_attributes.mli | 4 +- compiler/frontend/ast_exp_handle_external.ml | 8 +- compiler/frontend/ast_external.ml | 111 ++++------ compiler/frontend/ast_external.mli | 16 +- compiler/frontend/ast_external_mk.ml | 50 +++-- compiler/frontend/ast_external_mk.mli | 26 ++- compiler/frontend/ast_external_process.ml | 48 ++--- compiler/frontend/ast_external_process.mli | 24 +-- compiler/frontend/ast_literal.ml | 4 + compiler/frontend/ast_literal.mli | 2 + compiler/frontend/bs_ast_invariant.ml | 69 ++++-- compiler/frontend/bs_ast_invariant.mli | 13 ++ compiler/frontend/bs_builtin_ppx.ml | 204 +++++------------- compiler/frontend/ppx_entry.ml | 5 + compiler/gentype/translate_signature.ml | 7 +- compiler/gentype/translation.ml | 5 +- compiler/ml/ast_helper.mli | 2 +- compiler/ml/ast_iterator.ml | 2 +- compiler/ml/ast_mapper_from0.ml | 2 +- compiler/ml/ast_mapper_to0.ml | 9 +- compiler/ml/external_ffi_types.ml | 54 ++--- compiler/ml/external_ffi_types.mli | 11 +- compiler/ml/outcometree.ml | 3 +- compiler/ml/parsetree.ml | 19 +- compiler/ml/pprintast.ml | 7 +- compiler/ml/primitive.ml | 39 ++-- compiler/ml/primitive.mli | 28 ++- compiler/ml/printast.ml | 6 +- compiler/ml/printtyp.ml | 11 +- compiler/ml/printtyped.ml | 12 +- compiler/ml/typedecl.ml | 39 +++- compiler/ml/typedtree.ml | 1 - compiler/ml/typedtree.mli | 1 - compiler/ml/typemod.ml | 51 ++++- compiler/syntax/src/res_core.ml | 2 +- compiler/syntax/src/res_outcome_printer.ml | 11 +- compiler/syntax/src/res_printer.ml | 6 +- .../tests/src/RelativeExternal.res | 16 ++ .../expected/CompletionDictExpression.res.txt | 20 ++ .../src/expected/RelativeExternal.res.txt | 44 ++++ ...nal_reserved_inline_primitive.res.expected | 9 + ...ng_101_external_arg_attribute.res.expected | 43 ++++ ...arning_101_floating_attribute.res.expected | 13 ++ .../warning_101_recursive_module.res.expected | 13 ++ ..._101_relative_module_external.res.expected | 14 ++ .../external_reserved_inline_primitive.res | 2 + .../warning_101_external_arg_attribute.res | 6 + .../warning_101_floating_attribute.res | 6 + .../fixtures/warning_101_recursive_module.res | 7 + .../warning_101_relative_module_external.res | 7 + tests/ounit_tests/ounit_ast_mapper0_tests.ml | 41 +++- .../ounit_tests/ounit_string_literal_tests.ml | 10 +- .../data/ast-mapping/Externals.res | 11 + .../ast-mapping/expected/Externals.res.txt | 13 ++ .../data/oprint/expected/oprint.resi.txt | 6 +- tests/syntax_tests/data/oprint/oprint.res | 5 + tests/syntax_tests/res_test.ml | 3 + tests/tests/src/inline_const.mjs | 6 + tests/tests/src/inline_const.res | 6 + tests/tests/src/inline_const.resi | 6 + tests/tests/src/relative_path.mjs | 64 ++++++ tests/tests/src/relative_path.res | 23 ++ tests/tests/src/relative_path_intf.mjs | 17 ++ tests/tests/src/relative_path_intf.res | 2 + tests/tests/src/relative_path_intf.resi | 2 + tests/tests/src/relative_path_use.mjs | 35 +++ tests/tests/src/relative_path_use.res | 15 ++ 73 files changed, 916 insertions(+), 482 deletions(-) create mode 100644 changes/external-unused-attribute-once.fix.md create mode 100644 changes/external-warning-attribute.fix.md create mode 100644 changes/inline-bigint-let.fix.md create mode 100644 changes/resolve-ffi-externals.internal.md create mode 100644 tests/analysis_tests/tests/src/RelativeExternal.res create mode 100644 tests/analysis_tests/tests/src/expected/RelativeExternal.res.txt create mode 100644 tests/build_tests/super_errors/expected/external_reserved_inline_primitive.res.expected create mode 100644 tests/build_tests/super_errors/expected/warning_101_external_arg_attribute.res.expected create mode 100644 tests/build_tests/super_errors/expected/warning_101_floating_attribute.res.expected create mode 100644 tests/build_tests/super_errors/expected/warning_101_recursive_module.res.expected create mode 100644 tests/build_tests/super_errors/expected/warning_101_relative_module_external.res.expected create mode 100644 tests/build_tests/super_errors/fixtures/external_reserved_inline_primitive.res create mode 100644 tests/build_tests/super_errors/fixtures/warning_101_external_arg_attribute.res create mode 100644 tests/build_tests/super_errors/fixtures/warning_101_floating_attribute.res create mode 100644 tests/build_tests/super_errors/fixtures/warning_101_recursive_module.res create mode 100644 tests/build_tests/super_errors/fixtures/warning_101_relative_module_external.res create mode 100644 tests/syntax_tests/data/ast-mapping/Externals.res create mode 100644 tests/syntax_tests/data/ast-mapping/expected/Externals.res.txt create mode 100644 tests/tests/src/relative_path_intf.mjs create mode 100644 tests/tests/src/relative_path_intf.res create mode 100644 tests/tests/src/relative_path_intf.resi create mode 100644 tests/tests/src/relative_path_use.mjs create mode 100644 tests/tests/src/relative_path_use.res diff --git a/changes/external-unused-attribute-once.fix.md b/changes/external-unused-attribute-once.fix.md new file mode 100644 index 00000000000..c59ed9f906d --- /dev/null +++ b/changes/external-unused-attribute-once.fix.md @@ -0,0 +1 @@ +- Report an unused attribute on a relative `@module` external once instead of twice. diff --git a/changes/external-warning-attribute.fix.md b/changes/external-warning-attribute.fix.md new file mode 100644 index 00000000000..16e2b44b175 --- /dev/null +++ b/changes/external-warning-attribute.fix.md @@ -0,0 +1 @@ +- `@warning` on an external, or a `@@warning` anywhere before it in the file, now applies to the warnings about its FFI attributes, such as an unused `@as`. diff --git a/changes/inline-bigint-let.fix.md b/changes/inline-bigint-let.fix.md new file mode 100644 index 00000000000..f73a0e7b178 --- /dev/null +++ b/changes/inline-bigint-let.fix.md @@ -0,0 +1 @@ +- Inline `@inline let` bigint constants like other literals, instead of warning that `@inline` cannot appear there. diff --git a/changes/resolve-ffi-externals.internal.md b/changes/resolve-ffi-externals.internal.md new file mode 100644 index 00000000000..5cdee50ab84 --- /dev/null +++ b/changes/resolve-ffi-externals.internal.md @@ -0,0 +1 @@ +- Keep resolved FFI specifications out of the parsetree, which now holds an external's primitive string as written. The type checker resolves each external once. diff --git a/compiler/core/lam_compile_external_call.ml b/compiler/core/lam_compile_external_call.ml index 1a63ba8642e..4c586cd9184 100644 --- a/compiler/core/lam_compile_external_call.ml +++ b/compiler/core/lam_compile_external_call.ml @@ -358,7 +358,7 @@ let translate_ffi (cxt : Lam_compile_context.t) arg_types ~(prim_name : string) E.new_ fn args) | ( (Decl_send _ | Decl_get _ | Decl_set _ | Decl_get_index | Decl_set_index), Some Module_itself ) -> - assert false (* rejected during digestion *) + assert false (* rejected during resolution *) | Decl_val {name}, _ when decl.effective_arity = 0 -> (* a global value *) let e = translate_scoped_module_val named_module name scopes in diff --git a/compiler/frontend/ast_attributes.ml b/compiler/frontend/ast_attributes.ml index ecd78c16218..84f1d93b11b 100644 --- a/compiler/frontend/ast_attributes.ml +++ b/compiler/frontend/ast_attributes.ml @@ -69,17 +69,10 @@ let prim_to_be_encoded (name : string) = not (first_char_special name) They are not considered externals, they are part of the language *) -let rs_externals (attrs : t) (pval_prim : Parsetree.primitive_repr option) = - match (attrs, pval_prim) with - | _, (None | Some (Prim_ffi _ | Prim_inline_const _)) -> false - (* [None] is a [val]; an already-digested external is not processed again *) - | [], Some (Prim_name name) -> - (* Not any attribute found *) - prim_to_be_encoded name - | _, Some (Prim_name name) -> - Ext_list.exists_fst attrs (fun ({txt} : string Asttypes.loc) -> - external_attrs |> Array.exists (fun (x : string) -> txt = x)) - || prim_to_be_encoded name +let is_ffi_external (attrs : t) (prim_name : string) = + Ext_list.exists_fst attrs (fun ({txt} : string Asttypes.loc) -> + external_attrs |> Array.exists (fun (x : string) -> txt = x)) + || prim_to_be_encoded prim_name let is_inline : attr -> bool = fun ({txt}, _) -> txt = "inline" diff --git a/compiler/frontend/ast_attributes.mli b/compiler/frontend/ast_attributes.mli index 16f7e2f9075..15ac1dd5429 100644 --- a/compiler/frontend/ast_attributes.mli +++ b/compiler/frontend/ast_attributes.mli @@ -50,7 +50,9 @@ val process_derive_type : t -> derive_attr * t val internal_expansive : attr -val rs_externals : t -> Parsetree.primitive_repr option -> bool +val is_ffi_external : t -> string -> bool +(** Whether an [external] with these attributes and primitive name is an FFI + external, as opposed to a compiler intrinsic. *) val is_gentype : attr -> bool diff --git a/compiler/frontend/ast_exp_handle_external.ml b/compiler/frontend/ast_exp_handle_external.ml index b392a6248f7..9a39126b063 100644 --- a/compiler/frontend/ast_exp_handle_external.ml +++ b/compiler/frontend/ast_exp_handle_external.ml @@ -32,8 +32,8 @@ let raw_expression loc ~is_function (exp : Parsetree.expression) = { exp with pexp_desc = - Ast_external_mk.local_external_apply loc - ~pval_prim:(Prim_name "#raw_expr") ~pval_type:(raw_type ()) [exp]; + Ast_external_mk.local_external_apply loc ~pval_prim:"#raw_expr" + ~pval_type:(raw_type ()) [exp]; pexp_attributes = (match !is_function with | None -> exp.pexp_attributes @@ -72,8 +72,8 @@ let raw_structure loc (exp : Parsetree.expression) = { exp with pexp_desc = - Ast_external_mk.local_external_apply loc - ~pval_prim:(Prim_name "#raw_stmt") ~pval_type:(raw_type ()) [exp]; + Ast_external_mk.local_external_apply loc ~pval_prim:"#raw_stmt" + ~pval_type:(raw_type ()) [exp]; } let handle_raw loc payload = diff --git a/compiler/frontend/ast_external.ml b/compiler/frontend/ast_external.ml index e2c121866ad..f948e917baf 100644 --- a/compiler/frontend/ast_external.ml +++ b/compiler/frontend/ast_external.ml @@ -22,77 +22,42 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) -let handle_external_in_sig (self : Ast_mapper.mapper) - (prim : Parsetree.value_description) (sigi : Parsetree.signature_item) : - Parsetree.signature_item = - let loc = prim.pval_loc in - let pval_type = self.typ self prim.pval_type in - let pval_attributes = self.attributes self prim.pval_attributes in - match prim.pval_prim with - | None -> Location.raise_errorf ~loc "empty primitive string" - | Some (Prim_ffi _ | Prim_inline_const _) -> - Location.raise_errorf ~loc "external declaration already processed" - | Some (Prim_name v) -> ( - match - Ast_external_process.handle_attributes_as_prim loc pval_type - pval_attributes v - with - | {pval_type; pval_prim; pval_attributes; no_inline_cross_module} -> +(* The resolver behind [Primitive.resolve_external], which the type checker + calls once per declaration: an [@inline] constant, an FFI external with its + specification, or an intrinsic. An FFI external's errors and warnings are + reported here, including unused attributes on its resolved form. *) +let resolve (value_desc : Parsetree.value_description) (prim_name : string) : + Primitive.resolved_external = + if prim_name = Ast_external_mk.inline_const_prim then + match Ast_external_mk.inline_const_of_declaration value_desc with + | Some c -> { - sigi with - psig_desc = - Psig_value - { - prim with - pval_type; - pval_prim = - (if no_inline_cross_module then None else Some pval_prim); - pval_attributes; - }; - }) - -let handle_external_in_stru (self : Ast_mapper.mapper) - (prim : Parsetree.value_description) (str : Parsetree.structure_item) : - Parsetree.structure_item = - let loc = prim.pval_loc in - let pval_type = self.typ self prim.pval_type in - let pval_attributes = self.attributes self prim.pval_attributes in - match prim.pval_prim with - | None -> Location.raise_errorf ~loc "empty primitive string" - | Some (Prim_ffi _ | Prim_inline_const _) -> - Location.raise_errorf ~loc "external declaration already processed" - | Some (Prim_name v) -> ( - match - Ast_external_process.handle_attributes_as_prim loc pval_type - pval_attributes v - with - | {pval_type; pval_prim; pval_attributes; no_inline_cross_module} -> - let external_result = - { - str with - pstr_desc = - Pstr_primitive - {prim with pval_type; pval_prim = Some pval_prim; pval_attributes}; - } - in - if not no_inline_cross_module then external_result - else - let open Ast_helper in - Str.include_ ~loc - (Incl.mk ~loc - (Mod.constraint_ ~loc - (Mod.structure ~loc [external_result]) - (Mty.signature ~loc - [ - { - psig_desc = - Psig_value - { - prim with - pval_type; - pval_prim = None; - pval_attributes; - }; - psig_loc = loc; - }; - ])))) + resolved_type = value_desc.pval_type; + resolved_attributes = []; + resolved_name = ""; + resolved_kind = Kind_inline_const c; + } + | None -> + Location.raise_errorf ~loc:value_desc.pval_loc + "\"%s\" is reserved for %@inline constants" prim_name + else if Ast_attributes.is_ffi_external value_desc.pval_attributes prim_name + then ( + let {Ast_external_process.pval_type; spec; pval_attributes} = + Ast_external_process.resolve value_desc.pval_loc value_desc.pval_type + value_desc.pval_attributes prim_name + in + Bs_ast_invariant.emit_external_warnings_on_resolved_external value_desc + ~pval_type ~pval_attributes; + { + resolved_type = pval_type; + resolved_attributes = pval_attributes; + resolved_name = prim_name; + resolved_kind = Kind_external spec; + }) + else + { + resolved_type = value_desc.pval_type; + resolved_attributes = value_desc.pval_attributes; + resolved_name = prim_name; + resolved_kind = Kind_intrinsic; + } diff --git a/compiler/frontend/ast_external.mli b/compiler/frontend/ast_external.mli index 140c453037f..f11ad6b827c 100644 --- a/compiler/frontend/ast_external.mli +++ b/compiler/frontend/ast_external.mli @@ -22,14 +22,8 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) -val handle_external_in_sig : - Ast_mapper.mapper -> - Parsetree.value_description -> - Parsetree.signature_item -> - Parsetree.signature_item - -val handle_external_in_stru : - Ast_mapper.mapper -> - Parsetree.value_description -> - Parsetree.structure_item -> - Parsetree.structure_item +val resolve : + Parsetree.value_description -> string -> Primitive.resolved_external +(** The resolver behind [Primitive.resolve_external]: an [@inline] constant, + an FFI external with its specification, or an intrinsic. Reports an FFI + external's errors and warnings. *) diff --git a/compiler/frontend/ast_external_mk.ml b/compiler/frontend/ast_external_mk.ml index 14926a6f8a3..b23ff70c554 100644 --- a/compiler/frontend/ast_external_mk.ml +++ b/compiler/frontend/ast_external_mk.ml @@ -22,7 +22,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) -let local_external_apply loc ~(pval_prim : Parsetree.primitive_repr) +let local_external_apply loc ~(pval_prim : string) ~(pval_type : Parsetree.core_type) (args : Parsetree.expression list) : Parsetree.expression_desc = let local_module_name = "J" and local_fun_name = "unsafe_expr" in @@ -45,18 +45,42 @@ let local_external_apply loc ~(pval_prim : Parsetree.primitive_repr) {txt = Ldot (Lident local_module_name, local_fun_name); loc}) (Ext_list.map args (fun x -> (Asttypes.Nolabel, x))) ) -let inline_const (c : External_ffi_types.inline_const) : - Parsetree.primitive_repr = - Prim_inline_const c +let inline_const_prim = "#rescript-inline" -let inline_string semantic = inline_const (Const_string semantic) +let inline_const_of_expression (expression : Parsetree.expression) : + External_ffi_types.inline_const option = + match (Ast_payload.unwrap_braces expression).pexp_desc with + | Pexp_constant (Pconst_string _) + | Pexp_template {source_segments = [_]; values = []} -> ( + match Ast_payload.semantic_string_of_expression expression with + | Some semantic -> Some (Const_string semantic) + | None -> assert false) + | Pexp_constant (Pconst_integer (s, None)) -> + Some (Const_int (Int32.of_string s)) + | Pexp_constant (Pconst_integer (s, Some 'n')) -> + let positive, digits = Bigint_utils.parse_bigint s in + Some (Const_bigint {positive; digits}) + | Pexp_constant (Pconst_float (s, None)) -> Some (Const_float s) + | Pexp_construct ({txt = Lident (("true" | "false") as txt)}, {txt = []}) -> + Some (Const_bool (txt = "true")) + | _ -> None -let inline_bool b = inline_const (Const_bool b) +let inline_const_declaration ~(attr_loc : Location.t) + (value_desc : Parsetree.value_description) + (expression : Parsetree.expression) : Parsetree.value_description = + { + value_desc with + pval_prim = Some inline_const_prim; + pval_jsx_component = None; + pval_attributes = + [ + ( {txt = "inline"; loc = attr_loc}, + PStr [Ast_helper.Str.eval ~loc:expression.pexp_loc expression] ); + ]; + } -let inline_int i = inline_const (Const_int i) - -let inline_bigint s = - let positive, digits = Bigint_utils.parse_bigint s in - inline_const (Const_bigint {positive; digits}) - -let inline_float s = inline_const (Const_float s) +let inline_const_of_declaration (value_desc : Parsetree.value_description) = + match value_desc.pval_attributes with + | [({txt = "inline"}, PStr [{pstr_desc = Pstr_eval (expression, _)}])] -> + inline_const_of_expression expression + | _ -> None diff --git a/compiler/frontend/ast_external_mk.mli b/compiler/frontend/ast_external_mk.mli index 2fdcaf17604..3e052ecf47c 100644 --- a/compiler/frontend/ast_external_mk.mli +++ b/compiler/frontend/ast_external_mk.mli @@ -24,7 +24,7 @@ val local_external_apply : Location.t -> - pval_prim:Parsetree.primitive_repr -> + pval_prim:string -> pval_type:Parsetree.core_type -> Parsetree.expression list -> Parsetree.expression_desc @@ -39,12 +39,24 @@ val local_external_apply : ]} *) -val inline_string : string -> Parsetree.primitive_repr +val inline_const_prim : string +(** The primitive string of an [@inline] constant's declaration *) -val inline_bool : bool -> Parsetree.primitive_repr +val inline_const_of_expression : + Parsetree.expression -> External_ffi_types.inline_const option +(** The constant an [@inline] literal denotes, if it is one an [@inline] + value can carry *) -val inline_int : int32 -> Parsetree.primitive_repr +val inline_const_declaration : + attr_loc:Location.t -> + Parsetree.value_description -> + Parsetree.expression -> + Parsetree.value_description +(** [inline_const_declaration ~attr_loc value_desc literal] turns [value_desc] + into the [external] the type checker resolves to an inline constant: its + primitive is [inline_const_prim] and its only attribute is + [@inline(literal)]. *) -val inline_bigint : string -> Parsetree.primitive_repr - -val inline_float : string -> Parsetree.primitive_repr +val inline_const_of_declaration : + Parsetree.value_description -> External_ffi_types.inline_const option +(** The constant of a declaration built by [inline_const_declaration] *) diff --git a/compiler/frontend/ast_external_process.ml b/compiler/frontend/ast_external_process.ml index 2efd51690a7..e31086d852f 100644 --- a/compiler/frontend/ast_external_process.ml +++ b/compiler/frontend/ast_external_process.ml @@ -391,13 +391,6 @@ let check_return_wrapper loc (wrapper : External_ffi_types.return_wrapper) if Ast_core_type.is_user_option result_type then wrapper else Bs_syntaxerr.err loc Expect_opt_in_bs_return_to_opt -type response = { - pval_type: Parsetree.core_type; - pval_prim: Parsetree.primitive_repr; - pval_attributes: Parsetree.attributes; - no_inline_cross_module: bool; -} - (* A fixed argument means what [@as(value) _] means, so decode it with the same reader. *) let fixed_arg_type @@ -906,10 +899,15 @@ let external_decl_of_non_obj (loc : Location.t) (st : external_desc) | {get_name = Some _} -> Location.raise_errorf ~loc "Attribute found that conflicts with %@get" +type resolution = { + pval_type: Parsetree.core_type; + spec: External_ffi_types.t; + pval_attributes: Parsetree.attributes; +} + (** Note that the passed [type_annotation] is already processed by visitor pattern before*) -let handle_attributes (loc : Location.t) (type_annotation : Parsetree.core_type) - (prim_attributes : Ast_attributes.t) (prim_name : string) : - Parsetree.core_type * External_ffi_types.t * Parsetree.attributes * bool = +let resolve (loc : Location.t) (type_annotation : Parsetree.core_type) + (prim_attributes : Ast_attributes.t) (prim_name : string) : resolution = let prim_name_with_source = {name = prim_name; source = External} in let result_type, arg_types_ty = (* Note this assumes external type is syntatic (no abstraction)*) @@ -925,7 +923,7 @@ let handle_attributes (loc : Location.t) (type_annotation : Parsetree.core_type) let _arity, new_type, spec = process_obj loc external_desc prim_name arg_types_ty result_type in - (new_type, spec, unused_attrs, false) + {pval_type = new_type; spec; pval_attributes = unused_attrs} else let splice = external_desc.splice in let arg_type_specs, args, arg_type_specs_length = @@ -1015,28 +1013,18 @@ let handle_attributes (loc : Location.t) (type_annotation : Parsetree.core_type) external_decl_of_non_obj loc external_desc prim_name_with_source arg_type_specs_length arg_type_specs in - let relative = External_ffi_types.check_decl ~loc decl ~prim_name in + External_ffi_types.check_decl ~loc decl ~prim_name; (* result type can not be labeled *) (* currently we don't process attributes of return type, in the future we may *) let return_wrapper = check_return_wrapper loc external_desc.return_wrapper result_type in - ( (match args with - | [] -> result_type - | _ -> Ast_helper.Typ.arrow ~loc args result_type), - External_ffi_types.ffi_bs arg_type_specs return_wrapper decl, - unused_attrs, - relative ) - -let handle_attributes_as_prim (pval_loc : Location.t) (typ : Ast_core_type.t) - (attrs : Ast_attributes.t) (prim_name : string) : response = - let pval_type, ffi, pval_attributes, no_inline_cross_module = - handle_attributes pval_loc typ attrs prim_name - in - { - pval_type; - pval_prim = Prim_ffi {name = prim_name; spec = ffi}; - pval_attributes; - no_inline_cross_module; - } + { + pval_type = + (match args with + | [] -> result_type + | _ -> Ast_helper.Typ.arrow ~loc args result_type); + spec = External_ffi_types.ffi_bs arg_type_specs return_wrapper decl; + pval_attributes = unused_attrs; + } diff --git a/compiler/frontend/ast_external_process.mli b/compiler/frontend/ast_external_process.mli index fb8a0d43024..7fdc5b02dc5 100644 --- a/compiler/frontend/ast_external_process.mli +++ b/compiler/frontend/ast_external_process.mli @@ -22,20 +22,16 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) -type response = { +type resolution = { pval_type: Parsetree.core_type; - pval_prim: Parsetree.primitive_repr; - pval_attributes: Parsetree.attributes; - no_inline_cross_module: bool; + (** The declared type, without the arguments FFI attributes erase *) + spec: External_ffi_types.t; + pval_attributes: Parsetree.attributes; (** Attributes not consumed *) } -val handle_attributes_as_prim : - Location.t -> Ast_core_type.t -> Ast_attributes.t -> string -> response -(** - [handle_attributes_as_prim - loc pval_name.txt pval_type pval_attributes pval_prim] - [pval_name.txt] is the name of identifier - [pval_prim] is the name of string literal - - return value is of [pval_type, pval_prim, new_attrs] -*) +val resolve : + Location.t -> Ast_core_type.t -> Ast_attributes.t -> string -> resolution +(** [resolve loc pval_type pval_attributes prim_name] applies the FFI + attributes of an [external] declaration. Errors are raised and warnings + reported for the declaration, and the attributes it consumes are marked + used. *) diff --git a/compiler/frontend/ast_literal.ml b/compiler/frontend/ast_literal.ml index 490e7624cfb..e26d51c9ca9 100644 --- a/compiler/frontend/ast_literal.ml +++ b/compiler/frontend/ast_literal.ml @@ -77,3 +77,7 @@ let type_int ?loc () = let type_float = Ast_helper.Typ.mk (Ptyp_constr ({txt = Lident "float"; loc = Location.none}, [])) + +let type_bigint = + Ast_helper.Typ.mk + (Ptyp_constr ({txt = Lident "bigint"; loc = Location.none}, [])) diff --git a/compiler/frontend/ast_literal.mli b/compiler/frontend/ast_literal.mli index 42e08c6462b..0bba3eaef1d 100644 --- a/compiler/frontend/ast_literal.mli +++ b/compiler/frontend/ast_literal.mli @@ -49,3 +49,5 @@ val type_bool : unit -> Parsetree.core_type val type_int : core_type_lit val type_float : Parsetree.core_type + +val type_bigint : Parsetree.core_type diff --git a/compiler/frontend/bs_ast_invariant.ml b/compiler/frontend/bs_ast_invariant.ml index 741c5f4f58a..d035e0ebba8 100644 --- a/compiler/frontend/bs_ast_invariant.ml +++ b/compiler/frontend/bs_ast_invariant.ml @@ -134,26 +134,20 @@ let emit_external_warnings : iterator = value_description = (fun self v -> match v with - | ({pval_loc; pval_prim = Some (Prim_name byte_name); pval_type} : - Parsetree.value_description) -> ( - match byte_name with - | ("%identity" | "%component_identity") - when not (Ast_core_type.is_arity_one pval_type) -> - Location.raise_errorf ~loc:pval_loc - "%s expects a function type of the form 'a => 'b (arity 1)" - byte_name - | _ -> - if byte_name <> "" then - let c = String.unsafe_get byte_name 0 in - if not (c = '%' || c = '#' || c = '?') then - Location.prerr_warning pval_loc - (Warnings.Bs_ffi_warning - (byte_name ^ " such externals are unsafe")) - else super.value_description self v - else - Location.prerr_warning pval_loc - (Warnings.Bs_ffi_warning - (byte_name ^ " such externals are unsafe"))) + | {pval_prim = Some prim_name} + when Ast_attributes.is_ffi_external v.pval_attributes prim_name -> + (* The type checker checks it in its resolved form, through + [Ast_external.resolve]. *) + () + | { + pval_loc; + pval_prim = Some (("%identity" | "%component_identity") as byte_name); + pval_type; + } + when not (Ast_core_type.is_arity_one pval_type) -> + Location.raise_errorf ~loc:pval_loc + "%s expects a function type of the form 'a => 'b (arity 1)" + byte_name | _ -> super.value_description self v); pat = (fun self (pat : Parsetree.pattern) -> @@ -190,6 +184,41 @@ let emit_external_warnings_on_structure (stru : Parsetree.structure) = let emit_external_warnings_on_signature (sigi : Parsetree.signature) = emit_external_warnings.signature emit_external_warnings sigi +(* Can the walk report something for this part of a resolved external? Its + [attribute] case doesn't look into payloads, so an attribute can only if + the walk checks its name; a type can through its attributes and the forms + this doesn't look into. Most resolved externals hold nothing to report, and + skipping the walk saves its allocations. *) +let attribute_may_report (({txt}, _) : Parsetree.attribute) = + is_checked_attribute txt || removed_ocaml_attribute txt <> None + +let rec type_may_report (ty : Parsetree.core_type) = + List.exists attribute_may_report ty.ptyp_attributes + || + match ty.ptyp_desc with + | Ptyp_any | Ptyp_var _ -> false + | Ptyp_arrow {params; ret} -> + List.exists + (function + | Parsetree.Parg_type {attrs; typ} -> + List.exists attribute_may_report attrs || type_may_report typ + | Parg_fixed _ -> true) + params + || type_may_report ret + | Ptyp_tuple args | Ptyp_constr (_, args) -> List.exists type_may_report args + | Ptyp_object _ | Ptyp_alias _ | Ptyp_variant _ | Ptyp_poly _ | Ptyp_package _ + | Ptyp_extension _ -> + true + +let emit_external_warnings_on_resolved_external + (value_desc : Parsetree.value_description) ~pval_type ~pval_attributes = + if + List.exists attribute_may_report pval_attributes + || type_may_report pval_type + then + super.value_description emit_external_warnings + {value_desc with pval_type; pval_prim = None; pval_attributes} + (* The PPX bridge renames the [ocaml.]-prefixed builtins a PPX emits to their bare names, so source written with them is checked before it reaches the bridge. *) diff --git a/compiler/frontend/bs_ast_invariant.mli b/compiler/frontend/bs_ast_invariant.mli index 25e97fbdcb3..4eedafd2ef5 100644 --- a/compiler/frontend/bs_ast_invariant.mli +++ b/compiler/frontend/bs_ast_invariant.mli @@ -34,10 +34,23 @@ val iter_warnings_on_stru : Parsetree.structure -> unit val iter_warnings_on_sigi : Parsetree.signature -> unit +(** These checks skip FFI externals: the declaration stays as written until + type checking, so its argument types still carry the attributes that + resolution consumes. [Ast_external] checks each one in its resolved form + with [emit_external_warnings_on_resolved_external]. *) + val emit_external_warnings_on_structure : Parsetree.structure -> unit val emit_external_warnings_on_signature : Parsetree.signature -> unit +val emit_external_warnings_on_resolved_external : + Parsetree.value_description -> + pval_type:Parsetree.core_type -> + pval_attributes:Parsetree.attributes -> + unit +(** Check an external in its resolved form: the declaration with the type and + the attributes resolution left *) + val check_removed_ocaml_spellings_on_structure : Parsetree.structure -> unit (** Reject the [ocaml.]-prefixed builtin attributes and extensions that are no longer supported. Run on source before external PPXs see it. *) diff --git a/compiler/frontend/bs_builtin_ppx.ml b/compiler/frontend/bs_builtin_ppx.ml index d7ace584c4a..e07b96a4de3 100644 --- a/compiler/frontend/bs_builtin_ppx.ml +++ b/compiler/frontend/bs_builtin_ppx.ml @@ -121,8 +121,7 @@ let expr_mapper ~async_context (self : mapper) (e : Parsetree.expression) = let source = "/" ^ pattern ^ "/" ^ flags in Ast_payload.validate_raw_source ~kind:Raw_re ~loc ~offset:0 source; let raw = - Ast_external_mk.local_external_apply loc - ~pval_prim:(Prim_name "#raw_expr") + Ast_external_mk.local_external_apply loc ~pval_prim:"#raw_expr" ~pval_type: (Ast_helper.Typ.arrow [ @@ -463,89 +462,28 @@ let signature_item_mapper (self : mapper) (sigi : Parsetree.signature_item) : Parsetree.signature_item = match sigi.psig_desc with | Psig_type (rf, tdcls) -> Ast_tdcls.handle_tdcls_in_sigi self sigi rf tdcls - | Psig_value ({pval_attributes; pval_prim} as value_desc) -> ( + | Psig_value {pval_prim = Some prim_name; pval_attributes} + when Ast_attributes.is_ffi_external pval_attributes prim_name -> + (* The type checker resolves it. *) + default_mapper.signature_item self sigi + | Psig_value ({pval_attributes} as value_desc) -> ( let pval_attributes = self.attributes self pval_attributes in - if Ast_attributes.rs_externals pval_attributes pval_prim then - Ast_external.handle_external_in_sig self value_desc sigi - else - match Ast_attributes.has_inline_payload pval_attributes with - | Some ((_, PStr [{pstr_desc = Pstr_eval (expression, _)}]) as attr) -> ( - match (Ast_payload.unwrap_braces expression).pexp_desc with - | Pexp_constant (Pconst_string _) - | Pexp_template {source_segments = [_]; values = []} -> - let semantic = - match Ast_payload.semantic_string_of_expression expression with - | Some semantic -> semantic - | None -> assert false - in - succeed attr pval_attributes; - { - sigi with - psig_desc = - Psig_value - { - value_desc with - pval_prim = Some (Ast_external_mk.inline_string semantic); - pval_jsx_component = None; - pval_attributes = []; - }; - } - | Pexp_constant (Pconst_integer (s, None)) -> - succeed attr pval_attributes; - let s = Int32.of_string s in - { - sigi with - psig_desc = - Psig_value - { - value_desc with - pval_prim = Some (Ast_external_mk.inline_int s); - pval_jsx_component = None; - pval_attributes = []; - }; - } - | Pexp_constant (Pconst_integer (s, Some 'n')) -> - succeed attr pval_attributes; - { - sigi with - psig_desc = - Psig_value - { - value_desc with - pval_prim = Some (Ast_external_mk.inline_bigint s); - pval_jsx_component = None; - pval_attributes = []; - }; - } - | Pexp_constant (Pconst_float (s, None)) -> - succeed attr pval_attributes; - { - sigi with - psig_desc = - Psig_value - { - value_desc with - pval_prim = Some (Ast_external_mk.inline_float s); - pval_jsx_component = None; - pval_attributes = []; - }; - } - | Pexp_construct ({txt = Lident (("true" | "false") as txt)}, {txt = []}) - -> - succeed attr pval_attributes; - { - sigi with - psig_desc = - Psig_value - { - value_desc with - pval_prim = Some (Ast_external_mk.inline_bool (txt = "true")); - pval_jsx_component = None; - pval_attributes = []; - }; - } - | _ -> default_mapper.signature_item self sigi) - | Some _ | None -> default_mapper.signature_item self sigi) + match Ast_attributes.has_inline_payload pval_attributes with + | Some + (({loc = attr_loc}, PStr [{pstr_desc = Pstr_eval (expression, _)}]) as + attr) -> ( + match Ast_external_mk.inline_const_of_expression expression with + | Some _ -> + succeed attr pval_attributes; + { + sigi with + psig_desc = + Psig_value + (Ast_external_mk.inline_const_declaration ~attr_loc value_desc + expression); + } + | None -> default_mapper.signature_item self sigi) + | Some _ | None -> default_mapper.signature_item self sigi) | _ -> default_mapper.signature_item self sigi let structure_item_mapper (self : mapper) (str : Parsetree.structure_item) : @@ -571,9 +509,6 @@ let structure_item_mapper (self : mapper) (str : Parsetree.structure_item) : (LetUnwrap_not_supported_in_position `Toplevel) | Pstr_type (rf, tdcls) (* [ {ptype_attributes} as tdcl ] *) -> Ast_tdcls.handle_tdcls_in_stru self str rf tdcls - | Pstr_primitive prim - when Ast_attributes.rs_externals prim.pval_attributes prim.pval_prim -> - Ast_external.handle_external_in_stru self prim str | Pstr_value ( Nonrecursive, [ @@ -591,78 +526,39 @@ let structure_item_mapper (self : mapper) (str : Parsetree.structure_item) : let has_inline_property = Ast_attributes.has_inline_payload pvb_attributes in - match - (has_inline_property, (Ast_payload.unwrap_braces pvb_expr).pexp_desc) - with - | ( Some attr, - ( Pexp_constant (Pconst_string _) - | Pexp_template {source_segments = [_]; values = []} ) ) -> - let semantic = - match Ast_payload.semantic_string_of_expression pvb_expr with - | Some semantic -> semantic - | None -> assert false - in - succeed attr pvb_attributes; - { - str with - pstr_desc = - Pstr_primitive - { - pval_name; - pval_type = Ast_literal.type_string (); - pval_loc = pvb_loc; - pval_jsx_component = None; - pval_attributes = []; - pval_prim = Some (Ast_external_mk.inline_string semantic); - }; - } - | Some attr, Pexp_constant (Pconst_integer (s, None)) -> - let s = Int32.of_string s in - succeed attr pvb_attributes; - { - str with - pstr_desc = - Pstr_primitive - { - pval_name; - pval_type = Ast_literal.type_int (); - pval_loc = pvb_loc; - pval_jsx_component = None; - pval_attributes = []; - pval_prim = Some (Ast_external_mk.inline_int s); - }; - } - | Some attr, Pexp_constant (Pconst_float (s, None)) -> - succeed attr pvb_attributes; - { - str with - pstr_desc = - Pstr_primitive - { - pval_name; - pval_type = Ast_literal.type_float; - pval_loc = pvb_loc; - pval_jsx_component = None; - pval_attributes = []; - pval_prim = Some (Ast_external_mk.inline_float s); - }; - } - | ( Some attr, - Pexp_construct ({txt = Lident (("true" | "false") as txt)}, {txt = []}) - ) -> + let inline_const = + match has_inline_property with + | None -> None + | Some attr -> ( + match Ast_external_mk.inline_const_of_expression pvb_expr with + | None -> None + | Some c -> Some (attr, c)) + in + match inline_const with + | Some ((({loc = attr_loc}, _) as attr), c) -> succeed attr pvb_attributes; + let pval_type = + match c with + | Const_string _ -> Ast_literal.type_string () + | Const_int _ -> Ast_literal.type_int () + | Const_float _ -> Ast_literal.type_float + | Const_bool _ -> Ast_literal.type_bool () + | Const_bigint _ -> Ast_literal.type_bigint + in { str with pstr_desc = Pstr_primitive - { - pval_name; - pval_type = Ast_literal.type_bool (); - pval_loc = pvb_loc; - pval_jsx_component = None; - pval_attributes = []; - pval_prim = Some (Ast_external_mk.inline_bool (txt = "true")); - }; + (Ast_external_mk.inline_const_declaration ~attr_loc + { + pval_name; + pval_type; + pval_loc = pvb_loc; + pval_jsx_component = None; + pval_attributes = []; + pval_prim = None; + } + pvb_expr); } | _ -> { diff --git a/compiler/frontend/ppx_entry.ml b/compiler/frontend/ppx_entry.ml index e59a6ec5a0c..4edcbe19c60 100644 --- a/compiler/frontend/ppx_entry.ml +++ b/compiler/frontend/ppx_entry.ml @@ -24,6 +24,11 @@ let unsafe_mapper = Bs_builtin_ppx.mapper +(* The type checker resolves externals through this hook. Every compiler + driver links this module, also when it type checks a parsed AST without + running the built-in PPX. *) +let () = Primitive.resolve_external := Ast_external.resolve + let rewrite_signature (ast : Parsetree.signature) : Parsetree.signature = Bs_ast_invariant.iter_warnings_on_sigi ast; Ast_config.process_sig ast; diff --git a/compiler/gentype/translate_signature.ml b/compiler/gentype/translate_signature.ml index 5e2d6a78e89..319d4e3d7af 100644 --- a/compiler/gentype/translate_signature.ml +++ b/compiler/gentype/translate_signature.ml @@ -113,7 +113,12 @@ and translate_signature_item ~config ~output_file_relative ~resolver ~type_env value_description.val_attributes |> Annotation.has_attribute Annotation.tag_is_gentype_import in - if value_description.val_prim <> None || is_import then + let is_primitive = + match value_description.val_val.val_kind with + | Val_prim _ -> true + | Val_reg -> false + in + if is_primitive || is_import then value_description |> Translation.translate_primitive ~config ~output_file_relative ~resolver ~type_env diff --git a/compiler/gentype/translation.ml b/compiler/gentype/translation.ml index 3ea3b38ee5f..95550c813bf 100644 --- a/compiler/gentype/translation.ml +++ b/compiler/gentype/translation.ml @@ -128,9 +128,8 @@ let translate_primitive ~config ~output_file_relative ~resolver ~type_env if !(Debug.translation ()) then Log_.item "Translate Primitive\n"; let value_name = (* external foo : someType = "abc" -- the extern name is "abc" *) - match value_description.val_prim with - | (Some (Prim_name name_of_extern) | Some (Prim_ffi {name = name_of_extern})) - when name_of_extern <> "" -> + match value_description.val_val.val_kind with + | Val_prim {prim_name = name_of_extern} when name_of_extern <> "" -> name_of_extern | _ -> value_description.val_id |> Ident.name in diff --git a/compiler/ml/ast_helper.mli b/compiler/ml/ast_helper.mli index dff5fe11a0d..2c737ba4d63 100644 --- a/compiler/ml/ast_helper.mli +++ b/compiler/ml/ast_helper.mli @@ -304,7 +304,7 @@ module Val : sig val mk : ?loc:loc -> ?attrs:attrs -> - ?prim:primitive_repr -> + ?prim:string -> str -> core_type -> value_description diff --git a/compiler/ml/ast_iterator.ml b/compiler/ml/ast_iterator.ml index fe9932dd5ca..6d5095b2af3 100644 --- a/compiler/ml/ast_iterator.ml +++ b/compiler/ml/ast_iterator.ml @@ -529,7 +529,7 @@ let default_iterator = type_extension = T.iter_type_extension; extension_constructor = T.iter_extension_constructor; value_description = - (fun this ({pval_name; pval_type; pval_prim = _; pval_loc} as vd) -> + (fun this ({pval_name; pval_type; pval_loc} as vd) -> iter_loc this pval_name; this.typ this pval_type; (* An iterator sees the component annotation as the attribute it was diff --git a/compiler/ml/ast_mapper_from0.ml b/compiler/ml/ast_mapper_from0.ml index ae6294dd74d..cdadf91bec3 100644 --- a/compiler/ml/ast_mapper_from0.ml +++ b/compiler/ml/ast_mapper_from0.ml @@ -1628,7 +1628,7 @@ let default_mapper = let prim = match pval_prim with | [] -> None - | [s] -> Some (Parsetree.Prim_name s) + | [s] -> Some s | _ :: _ :: _ -> Location.raise_errorf ~loc:pval_loc "An external declaration can carry only a single primitive string" diff --git a/compiler/ml/ast_mapper_to0.ml b/compiler/ml/ast_mapper_to0.ml index 373652bc7ba..09e53291459 100644 --- a/compiler/ml/ast_mapper_to0.ml +++ b/compiler/ml/ast_mapper_to0.ml @@ -1063,14 +1063,7 @@ let default_mapper = let prim = match pval_prim with | None -> [] - | Some (Prim_name s) -> [s] - | Some (Prim_ffi _ | Prim_inline_const _) -> - (* External PPXes run before the frontend digests externals, and - nothing else crosses this bridge, so a digested external can - never legitimately reach it. *) - Location.raise_errorf ~loc:pval_loc - "External declarations already processed for compilation cannot \ - be converted for an external PPX" + | Some s -> [s] in (* v0 has no component node: PPXs see the [@react.component] attribute, and [Ast_helper.Val.mk] takes it out again on the way diff --git a/compiler/ml/external_ffi_types.ml b/compiler/ml/external_ffi_types.ml index b32f27ede0e..c51200142af 100644 --- a/compiler/ml/external_ffi_types.ml +++ b/compiler/ml/external_ffi_types.ml @@ -40,7 +40,7 @@ type arg_type = External_arg_spec.attr type arg_label = External_arg_spec.label (* The declaration, as the attribute language states it. The backend - compiles it directly; digestion validates it with [check_decl]. *) + compiles it directly; resolution validates it with [check_decl]. *) type module_source = | Module_named of external_module_name (* @module("...") payload forms *) | Module_itself @@ -145,17 +145,12 @@ let check_external_module_name ?loc x = Location.raise_errorf ?loc "empty name encountered" | _ -> () -(* Validation of a declaration; returns whether the binding refers to a - package-relative path (which disables cross-module inlining). The checks - mirror the historical per-runtime-shape checks exactly, including their - asymmetries (a zero-arity value also checks its own name for - relativeness; an applied one checks the module name for emptiness). *) -let check_decl ?loc (decl : external_decl) ~prim_name : bool = - let xrelative = ref false in - let upgrade bool = if not !xrelative then xrelative := bool in - (match decl.module_ with +(* Validation of a declaration. The checks mirror the historical + per-runtime-shape checks exactly, including their asymmetry: an applied + value checks its module name for emptiness, a zero-arity one doesn't. *) +let check_decl ?loc (decl : external_decl) ~prim_name = + match decl.module_ with | Some Module_itself -> - upgrade (is_package_relative_path prim_name); if prim_name = "" then Location.raise_errorf ?loc "empty name encountered" | (None | Some (Module_named _)) as module_ -> ( let emn = @@ -165,27 +160,34 @@ let check_decl ?loc (decl : external_decl) ~prim_name : bool = in match decl.kind with | Decl_val {name} -> - if decl.effective_arity = 0 then ( - upgrade (is_package_relative_path name); - emn - |> Option.iter (fun emn -> - upgrade (is_package_relative_path emn.bundle)); - valid_global_name ?loc name) - else ( - emn - |> Option.iter (fun emn -> - upgrade (is_package_relative_path emn.bundle)); + if decl.effective_arity <> 0 then Option.iter (fun emn -> check_external_module_name ?loc emn) emn; - valid_global_name ?loc name) + valid_global_name ?loc name | Decl_new {name} -> - emn - |> Option.iter (fun emn -> upgrade (is_package_relative_path emn.bundle)); Option.iter (fun emn -> check_external_module_name ?loc emn) emn; valid_global_name ?loc name | Decl_send {name} | Decl_set {name} | Decl_get {name} -> valid_method_name ?loc name - | Decl_get_index | Decl_set_index -> ())); - !xrelative + | Decl_get_index | Decl_set_index -> ()) + +(* Does the declaration name a package-relative path? A zero-arity value also + counts its own name. *) +let is_relative (decl : external_decl) ~prim_name = + match decl.module_ with + | Some Module_itself -> is_package_relative_path prim_name + | (None | Some (Module_named _)) as module_ -> ( + let bundle_relative = + match module_ with + | Some (Module_named emn) -> is_package_relative_path emn.bundle + | _ -> false + in + match decl.kind with + | Decl_val {name} -> + bundle_relative + || (decl.effective_arity = 0 && is_package_relative_path name) + | Decl_new _ -> bundle_relative + | Decl_send _ | Decl_set _ | Decl_get _ | Decl_get_index | Decl_set_index -> + false) (* Can an implementation's spec satisfy an interface's spec during signature inclusion? Equal specs always can. Object-creation specs compare their diff --git a/compiler/ml/external_ffi_types.mli b/compiler/ml/external_ffi_types.mli index a4b9afa1902..2e3c3d773e4 100644 --- a/compiler/ml/external_ffi_types.mli +++ b/compiler/ml/external_ffi_types.mli @@ -40,7 +40,7 @@ type arg_type = External_arg_spec.attr type arg_label = External_arg_spec.label (* The declaration, as the attribute language states it. The backend - compiles it directly; digestion validates it with [check_decl]. *) + compiles it directly; resolution validates it with [check_decl]. *) type module_source = | Module_named of external_module_name (* @module("...") payload forms *) | Module_itself @@ -89,9 +89,12 @@ type t = private | Ffi_bs of External_arg_spec.params * return_wrapper * external_decl | Ffi_obj_create of External_arg_spec.obj_params -val check_decl : ?loc:Location.t -> external_decl -> prim_name:string -> bool -(** Validation of a declaration; returns whether the binding refers to a - package-relative path (which disables cross-module inlining). *) +val check_decl : ?loc:Location.t -> external_decl -> prim_name:string -> unit +(** Validation of a declaration *) + +val is_relative : external_decl -> prim_name:string -> bool +(** Does the declaration refer to a package-relative path? Other modules must + not inline such an external, since the path is relative to its own file. *) val inclusion_compatible : t -> t -> bool (** [inclusion_compatible impl intf]: can an implementation's spec satisfy an diff --git a/compiler/ml/outcometree.ml b/compiler/ml/outcometree.ml index 07406769969..15e96a7a382 100644 --- a/compiler/ml/outcometree.ml +++ b/compiler/ml/outcometree.ml @@ -93,7 +93,8 @@ and out_type_extension = { and out_val_decl = { oval_name: string; oval_type: out_type; - oval_prim: Parsetree.primitive_repr option; + oval_prim: Primitive.description option; + (* resolved, so the printer can render its FFI attributes *) oval_attributes: out_attribute list; } and out_rec_status = Orec_not | Orec_first | Orec_next diff --git a/compiler/ml/parsetree.ml b/compiler/ml/parsetree.ml index be911e00ad0..094a91ca2d7 100644 --- a/compiler/ml/parsetree.ml +++ b/compiler/ml/parsetree.ml @@ -538,7 +538,11 @@ and fun_param = { and value_description = { pval_name: string loc; pval_type: core_type; - pval_prim: primitive_repr option; + pval_prim: string option; + (* The primitive string as written: an intrinsic ("%identity", + "#raw_expr") or the JS name of an FFI external. Its FFI attributes + stay in [pval_attributes] and on the argument types; the type + checker resolves them through [Primitive.resolve_external]. *) pval_jsx_component: jsx_component option; (* The [@react.component] annotation, taken out of the attributes when the description is built. *) @@ -570,19 +574,8 @@ and jsx_component_namespace = Pjc_react | Pjc_jsx (* val x: T (prim = None) - external x: T = "s" (prim = Some _) + external x: T = "s" (prim = Some "s") *) -and primitive_repr = - | Prim_name of string - (* as written in the source: an intrinsic ("%identity", "#raw_expr") - or the not-yet-digested JS name of an FFI external *) - | Prim_ffi of {name: string; spec: External_ffi_types.t} - (* produced by the frontend digestion of an FFI external's - attributes; never observed by external PPXes, which run before - digestion *) - | Prim_inline_const of External_ffi_types.inline_const -(* an [@inline()] value declaration: a compile-time constant, - not an FFI; produced by digestion like [Prim_ffi] *) (* Type declarations *) and type_declaration = { diff --git a/compiler/ml/pprintast.ml b/compiler/ml/pprintast.ml index 5ed187bbddc..338c0e185c9 100644 --- a/compiler/ml/pprintast.ml +++ b/compiler/ml/pprintast.ml @@ -996,12 +996,7 @@ and value_description ctxt f x = (fun f x -> match x.pval_prim with | None -> () - | Some (Prim_name s) -> pp f "@ =@ %a" constant_string s - | Some (Prim_ffi {name}) -> - pp f "@ =@ %a@ %a" constant_string name constant_string - "#rescript-external" - | Some (Prim_inline_const _) -> - pp f "@ =@ %a" constant_string "#rescript-inline") + | Some s -> pp f "@ =@ %a" constant_string s) x and extension ctxt f (s, e) = pp f "@[<2>[%%%s@ %a]@]" s.txt (payload ctxt) e diff --git a/compiler/ml/primitive.ml b/compiler/ml/primitive.ml index 2506e167e4c..6cf77814a58 100644 --- a/compiler/ml/primitive.ml +++ b/compiler/ml/primitive.ml @@ -16,7 +16,6 @@ (* Description of primitive functions *) open Misc -open Parsetree type prim_kind = | Kind_intrinsic @@ -49,15 +48,19 @@ let coercible (impl : description) (intf : description) = External_ffi_types.inclusion_compatible impl_ffi intf_ffi | _ -> false -let parse_declaration (valdecl : Parsetree.value_description) ~arity - ~from_constructor = - let name, kind = - match valdecl.pval_prim with - | Some (Prim_name name) -> (name, Kind_intrinsic) - | Some (Prim_ffi {name; spec}) -> (name, Kind_external spec) - | Some (Prim_inline_const c) -> ("", Kind_inline_const c) - | None -> fatal_error "Primitive.parse_declaration" - in +type resolved_external = { + resolved_type: Parsetree.core_type; + resolved_attributes: Parsetree.attributes; + resolved_name: string; + resolved_kind: prim_kind; +} + +let resolve_external : + (Parsetree.value_description -> string -> resolved_external) ref = + ref (fun (_ : Parsetree.value_description) (_ : string) -> + fatal_error "Primitive.resolve_external: no resolver registered") + +let make ~name ~kind ~arity ~from_constructor = { prim_name = name; prim_arity = arity; @@ -65,13 +68,9 @@ let parse_declaration (valdecl : Parsetree.value_description) ~arity prim_from_constructor = from_constructor; } -open Outcometree - -let print p osig_val_decl = - let repr : Parsetree.primitive_repr = - match p.prim_kind with - | Kind_intrinsic -> Prim_name p.prim_name - | Kind_external spec -> Prim_ffi {name = p.prim_name; spec} - | Kind_inline_const c -> Prim_inline_const c - in - {osig_val_decl with oval_prim = Some repr; oval_attributes = []} +let no_cross_module_inline (d : description) = + match d.prim_kind with + | Kind_external (Ffi_bs (_, _, decl)) -> + External_ffi_types.is_relative decl ~prim_name:d.prim_name + | Kind_external (Ffi_obj_create _) | Kind_intrinsic | Kind_inline_const _ -> + false diff --git a/compiler/ml/primitive.mli b/compiler/ml/primitive.mli index 2469db60eab..91b181edaf7 100644 --- a/compiler/ml/primitive.mli +++ b/compiler/ml/primitive.mli @@ -35,14 +35,36 @@ val with_arity : (* Invariant [List.length d.prim_native_repr_args = d.prim_arity] *) -val parse_declaration : - Parsetree.value_description -> +val make : + name:string -> + kind:prim_kind -> arity:int -> from_constructor:bool -> description -val print : description -> Outcometree.out_val_decl -> Outcometree.out_val_decl +type resolved_external = { + resolved_type: Parsetree.core_type; + (** The declared type, rewritten where FFI attributes erase or reshape + arguments ([@as] constants, [@ignore], [@obj] results). *) + resolved_attributes: Parsetree.attributes; + (** The declaration's attributes that resolution did not consume. *) + resolved_name: string; + resolved_kind: prim_kind; +} +(** An [external] declaration after its FFI attributes are applied. *) + +val resolve_external : + (Parsetree.value_description -> string -> resolved_external) ref +(** [!resolve_external value_desc prim] resolves an [external] declaration + whose primitive string is [prim] during type checking. FFI resolution lives in the frontend, above this library, which + registers it before any source is type checked. *) val coercible : description -> description -> bool (** Can an implementation's primitive satisfy an interface's during signature inclusion? *) + +val no_cross_module_inline : description -> bool +(** An external that names a package-relative path, such as + [@module("./x")]. The path is relative to the file that declares it, so + the module exports it as a value and other modules call that value instead + of inlining the external. *) diff --git a/compiler/ml/printast.ml b/compiler/ml/printast.ml index f5ea0eede7e..1575e70ae16 100644 --- a/compiler/ml/printast.ml +++ b/compiler/ml/printast.ml @@ -526,11 +526,7 @@ and value_description i ppf x = core_type (i + 1) ppf x.pval_type; match x.pval_prim with | None -> () - | Some (Prim_name s) -> string (i + 1) ppf s - | Some (Prim_ffi {name}) -> - string (i + 1) ppf name; - line (i + 1) ppf "\n" - | Some (Prim_inline_const _) -> line (i + 1) ppf "\n" + | Some s -> string (i + 1) ppf s and type_parameter i ppf (x, _variance) = core_type i ppf x diff --git a/compiler/ml/printtyp.ml b/compiler/ml/printtyp.ml index bf36350da19..b17c892109f 100644 --- a/compiler/ml/printtyp.ml +++ b/compiler/ml/printtyp.ml @@ -1070,15 +1070,12 @@ let extension_constructor id ppf ext = let tree_of_value_description id decl = let id = Ident.name id in let ty = tree_of_type_scheme decl.val_type in - let vd = - {oval_name = id; oval_type = ty; oval_prim = None; oval_attributes = []} - in - let vd = + let oval_prim = match decl.val_kind with - | Val_prim p -> Primitive.print p vd - | _ -> vd + | Val_prim p -> Some p + | Val_reg -> None in - Osig_value vd + Osig_value {oval_name = id; oval_type = ty; oval_prim; oval_attributes = []} let value_description id ppf decl = !Oprint.out_sig_item ppf (tree_of_value_description id decl) diff --git a/compiler/ml/printtyped.ml b/compiler/ml/printtyped.ml index 10687d520f2..6faa2dd8d9e 100644 --- a/compiler/ml/printtyped.ml +++ b/compiler/ml/printtyped.ml @@ -424,13 +424,11 @@ and value_description i ppf x = x.val_loc; attributes i ppf x.val_attributes; core_type (i + 1) ppf x.val_desc; - match x.val_prim with - | None -> () - | Some (Prim_name s) -> string (i + 1) ppf s - | Some (Prim_ffi {name}) -> - string (i + 1) ppf name; - line (i + 1) ppf "\n" - | Some (Prim_inline_const _) -> line (i + 1) ppf "\n" + match x.val_val.val_kind with + | Val_reg -> () + | Val_prim {prim_kind = Kind_inline_const _} -> + line (i + 1) ppf "\n" + | Val_prim {prim_name} -> string (i + 1) ppf prim_name and type_parameter i ppf (x, _variance) = core_type i ppf x diff --git a/compiler/ml/typedecl.ml b/compiler/ml/typedecl.ml index a4baa99ccb6..f2d36619ad2 100644 --- a/compiler/ml/typedecl.ml +++ b/compiler/ml/typedecl.ml @@ -1923,14 +1923,30 @@ let parse_arity env _core_type ty = (* Translate a value declaration *) let transl_value_decl env loc valdecl = - let cty = Typetexp.transl_type_scheme env valdecl.pval_type in + let pval_type, pval_attributes, prim = + match valdecl.pval_prim with + | None -> (valdecl.pval_type, valdecl.pval_attributes, None) + | Some txt -> + let { + Primitive.resolved_type; + resolved_attributes; + resolved_name; + resolved_kind; + } = + !Primitive.resolve_external valdecl txt + in + (resolved_type, resolved_attributes, Some (resolved_name, resolved_kind)) + in + let cty = Typetexp.transl_type_scheme env pval_type in let ty = cty.ctyp_type in (* The typed tree keeps the attributes as written: only the JSX transform reads the component annotation, and a declaration it leaves alone keeps the attribute, as it always has. *) - let attributes = Ast_helper.Val.description_attributes valdecl in + let attributes = + Ast_helper.Val.description_attributes {valdecl with pval_attributes} + in let v = - match valdecl.pval_prim with + match prim with | None when Env.is_in_signature env -> { val_type = ty; @@ -1945,18 +1961,24 @@ let transl_value_decl env loc valdecl = declaration. A bare `val x: int` in a .res is also rejected at parse time. *) assert false - | Some _ -> - let arity, from_constructor = parse_arity env valdecl.pval_type ty in - let prim = Primitive.parse_declaration valdecl ~arity ~from_constructor in + | Some (name, kind) -> + let arity, from_constructor = parse_arity env pval_type ty in + let prim = Primitive.make ~name ~kind ~arity ~from_constructor in if prim.prim_arity = 0 && prim.prim_kind = Kind_intrinsic && (prim.prim_name = "" || (prim.prim_name.[0] <> '%' && prim.prim_name.[0] <> '#')) - then raise (Error (valdecl.pval_type.ptyp_loc, Null_arity_external)); + then raise (Error (pval_type.ptyp_loc, Null_arity_external)); { val_type = ty; - val_kind = Val_prim prim; + val_kind = + (* Other modules call an external with a relative path through the + value its module exports. A structure exports it with + [Typemod]'s wrapper. *) + (if Env.is_in_signature env && Primitive.no_cross_module_inline prim + then Val_reg + else Val_prim prim); Types.val_loc = loc; val_attributes = attributes; } @@ -1971,7 +1993,6 @@ let transl_value_decl env loc valdecl = val_name = valdecl.pval_name; val_desc = cty; val_val = v; - val_prim = valdecl.pval_prim; val_loc = valdecl.pval_loc; val_attributes = attributes; } diff --git a/compiler/ml/typedtree.ml b/compiler/ml/typedtree.ml index 64371b04317..4b42e0fbdf7 100644 --- a/compiler/ml/typedtree.ml +++ b/compiler/ml/typedtree.ml @@ -384,7 +384,6 @@ and value_description = { val_name: string loc; val_desc: core_type; val_val: Types.value_description; - val_prim: Parsetree.primitive_repr option; val_loc: Location.t; val_attributes: attribute list; } diff --git a/compiler/ml/typedtree.mli b/compiler/ml/typedtree.mli index 01cbb5eae71..4c45443d73e 100644 --- a/compiler/ml/typedtree.mli +++ b/compiler/ml/typedtree.mli @@ -511,7 +511,6 @@ and value_description = { val_name: string loc; val_desc: core_type; val_val: Types.value_description; - val_prim: Parsetree.primitive_repr option; val_loc: Location.t; val_attributes: attributes; } diff --git a/compiler/ml/typemod.ml b/compiler/ml/typemod.ml index 4fe073a2f10..583b4322019 100644 --- a/compiler/ml/typemod.ml +++ b/compiler/ml/typemod.ml @@ -1469,9 +1469,56 @@ and type_structure funct_body anchor env sstr = Sig_value (id, vd)) (let_bound_idents defs), newenv ) - | Pstr_primitive sdesc -> + | Pstr_primitive sdesc -> ( let desc, newenv = Typedecl.transl_value_decl env loc sdesc in - (Tstr_primitive desc, [Sig_value (desc.val_id, desc.val_val)], newenv) + let item = Sig_value (desc.val_id, desc.val_val) in + match desc.val_val.val_kind with + | Val_prim prim when Primitive.no_cross_module_inline prim -> + (* An external with a relative path, such as [@module("./x")], must + not be inlined in other modules, so the module exports it as a + value: [include (struct external x = ... end : {let x: t})]. *) + let structure = + { + mod_desc = + Tmod_structure + { + str_items = + [ + { + str_desc = Tstr_primitive desc; + str_loc = loc; + str_env = env; + }; + ]; + str_type = [item]; + str_final_env = newenv; + }; + mod_type = Mty_signature [item]; + mod_env = env; + mod_attributes = []; + mod_loc = loc; + } + in + let value_sig = + Mty_signature + [Sig_value (desc.val_id, {desc.val_val with val_kind = Val_reg})] + in + let modl = wrap_constraint env structure value_sig Tmodtype_implicit in + (* Rename the identifier, as an [include] does *) + let sg = + Subst.signature Subst.identity + (extract_sig_open env loc modl.mod_type) + in + let incl = + { + incl_mod = modl; + incl_type = sg; + incl_attributes = []; + incl_loc = loc; + } + in + (Tstr_include incl, sg, Env.add_signature sg env) + | _ -> (Tstr_primitive desc, [item], newenv)) | Pstr_type (rec_flag, sdecls) -> List.iter (fun decl -> check_name check_type names decl.ptype_name) sdecls; let decls, newenv = Typedecl.transl_type_decl env rec_flag sdecls in diff --git a/compiler/syntax/src/res_core.ml b/compiler/syntax/src/res_core.ml index 9e68773b8cf..e4939e779a6 100644 --- a/compiler/syntax/src/res_core.ml +++ b/compiler/syntax/src/res_core.ml @@ -6287,7 +6287,7 @@ and parse_external_def ~attrs ~start_pos p = match Parser.peek p with | String s -> Parser.next p; - Some (Parsetree.Prim_name s) + Some s | _ -> Parser.err ~start_pos:equal_start ~end_pos:equal_end p (Diagnostics.message diff --git a/compiler/syntax/src/res_outcome_printer.ml b/compiler/syntax/src/res_outcome_printer.ml index c3a85cfa99e..da8ddeffe8a 100644 --- a/compiler/syntax/src/res_outcome_printer.ml +++ b/compiler/syntax/src/res_outcome_printer.ml @@ -456,7 +456,7 @@ let print_type_parameter_doc (typ, (co, cn)) = (if typ = "_" then Doc.text "_" else Doc.text ("'" ^ typ)); ] -(* Print a digested FFI declaration as the surface attributes the user +(* Print a resolved FFI declaration as the surface attributes the user wrote; the stored form is the declaration itself. *) let print_inline_const_doc (c : External_ffi_types.inline_const) = @@ -486,7 +486,7 @@ let print_external_module_doc (emn : External_ffi_types.external_module_name) = let with_fields = import_attributes |> List.map (fun (k, v) -> - (* digestion stores the source key [type_] as [type]; other + (* resolution stores the source key [type_] as [type]; other keys are stored as written, including exotic ones from escaped idents (\"some-identifier"), which must print escaped again to be writable source *) @@ -589,14 +589,15 @@ let rec print_out_sig_item_doc ?(print_name_as_is = false) let ffi_attrs, keyword, prim_name = match value_decl.oval_prim with | None -> (Doc.nil, "let ", None) - | Some (Prim_name s) -> (Doc.nil, "external ", Some s) - | Some (Prim_inline_const c) -> + | Some {prim_kind = Kind_intrinsic; prim_name} -> + (Doc.nil, "external ", Some prim_name) + | Some {prim_kind = Kind_inline_const c} -> (* surface syntax: [@inline("hello") let f: string] *) ( Doc.concat [Doc.text "@inline("; print_inline_const_doc c; Doc.text ") "], "let ", None ) - | Some (Prim_ffi {name; spec}) -> ( + | Some {prim_kind = Kind_external spec; prim_name = name} -> ( match spec with | Ffi_obj_create _ -> (Doc.text "@obj ", "external ", Some name) | Ffi_bs (_params, return_wrapper, decl) -> diff --git a/compiler/syntax/src/res_printer.ml b/compiler/syntax/src/res_printer.ml index 6c673f5ac11..c760331986c 100644 --- a/compiler/syntax/src/res_printer.ml +++ b/compiler/syntax/src/res_printer.ml @@ -1354,10 +1354,8 @@ and print_value_description ~state value_description cmt_tbl = Doc.line; (let s = match value_description.pval_prim with - | Some (Prim_name s) | Some (Prim_ffi {name = s}) - -> - s - | Some (Prim_inline_const _) | None -> "" + | Some s -> s + | None -> "" in Doc.concat [Doc.text "\""; Doc.text s; Doc.text "\""]); ]); diff --git a/tests/analysis_tests/tests/src/RelativeExternal.res b/tests/analysis_tests/tests/src/RelativeExternal.res new file mode 100644 index 00000000000..5c053f9b7b6 --- /dev/null +++ b/tests/analysis_tests/tests/src/RelativeExternal.res @@ -0,0 +1,16 @@ +// An external with a relative path is exported as a value. +@module("./local") external relative: int => int = "relative" +// ^hov + +let a = relative(1) +// ^hov + +let b = relative(2) +// ^ref + +module Nested = { + @module("./local") external nested: int => int = "nested" +} + +let c = Nested.nested(3) +// ^def diff --git a/tests/analysis_tests/tests/src/expected/CompletionDictExpression.res.txt b/tests/analysis_tests/tests/src/expected/CompletionDictExpression.res.txt index 4d477184d84..823a8492014 100644 --- a/tests/analysis_tests/tests/src/expected/CompletionDictExpression.res.txt +++ b/tests/analysis_tests/tests/src/expected/CompletionDictExpression.res.txt @@ -167,6 +167,16 @@ Path color "label": "ReferencesWithInterface", "tags": [] }, + { + "data": { + "modulePath": "RelativeExternal", + "filePath": "src/CompletionDictExpression.res" + }, + "detail": "module RelativeExternal", + "kind": 9, + "label": "RelativeExternal", + "tags": [] + }, { "data": { "modulePath": "Rename", @@ -883,6 +893,16 @@ Path color "label": "ReferencesWithInterface", "tags": [] }, + { + "data": { + "modulePath": "RelativeExternal", + "filePath": "src/CompletionDictExpression.res" + }, + "detail": "module RelativeExternal", + "kind": 9, + "label": "RelativeExternal", + "tags": [] + }, { "data": { "modulePath": "Rename", diff --git a/tests/analysis_tests/tests/src/expected/RelativeExternal.res.txt b/tests/analysis_tests/tests/src/expected/RelativeExternal.res.txt new file mode 100644 index 00000000000..f2a80583c64 --- /dev/null +++ b/tests/analysis_tests/tests/src/expected/RelativeExternal.res.txt @@ -0,0 +1,44 @@ +Hover src/RelativeExternal.res 1:30 +{ + "contents": { "kind": "markdown", "value": "```rescript\nint => int\n```" } +} + +Hover src/RelativeExternal.res 4:9 +{ + "contents": { "kind": "markdown", "value": "```rescript\nint => int\n```" } +} + +References src/RelativeExternal.res 7:10 +[ + { + "range": { + "end": { "character": 61, "line": 1 }, + "start": { "character": 0, "line": 1 } + }, + "uri": "file:///RelativeExternal.res" + }, + { + "range": { + "end": { "character": 16, "line": 4 }, + "start": { "character": 8, "line": 4 } + }, + "uri": "file:///RelativeExternal.res" + }, + { + "range": { + "end": { "character": 16, "line": 7 }, + "start": { "character": 8, "line": 7 } + }, + "uri": "file:///RelativeExternal.res" + } +] + +Definition src/RelativeExternal.res 14:17 +{ + "range": { + "end": { "character": 59, "line": 11 }, + "start": { "character": 2, "line": 11 } + }, + "uri": "file:///RelativeExternal.res" +} + diff --git a/tests/build_tests/super_errors/expected/external_reserved_inline_primitive.res.expected b/tests/build_tests/super_errors/expected/external_reserved_inline_primitive.res.expected new file mode 100644 index 00000000000..78dc71a1071 --- /dev/null +++ b/tests/build_tests/super_errors/expected/external_reserved_inline_primitive.res.expected @@ -0,0 +1,9 @@ + + We've found a bug for you! + /.../fixtures/external_reserved_inline_primitive.res:2:1-41 + + 1 │ // This primitive name is only for @inline constants. + 2 │ external answer: int = "#rescript-inline" + 3 │ + + "#rescript-inline" is reserved for @inline constants \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/warning_101_external_arg_attribute.res.expected b/tests/build_tests/super_errors/expected/warning_101_external_arg_attribute.res.expected new file mode 100644 index 00000000000..1b9c94fa4d8 --- /dev/null +++ b/tests/build_tests/super_errors/expected/warning_101_external_arg_attribute.res.expected @@ -0,0 +1,43 @@ + + Warning number 101 (configured as error) + /.../fixtures/warning_101_external_arg_attribute.res:2:27-29 + + 1 │ type t + 2 │ @send external first: (t, @as("x") int) => unit = "first" + 3 │ @send external second: (t, @as("y") int) => unit = "second" + 4 │ + + Unused attribute: @as +This attribute has no effect here. +For example, some attributes are only meaningful in externals. + + + + Warning number 101 (configured as error) + /.../fixtures/warning_101_external_arg_attribute.res:3:28-30 + + 1 │ type t + 2 │ @send external first: (t, @as("x") int) => unit = "first" + 3 │ @send external second: (t, @as("y") int) => unit = "second" + 4 │ + 5 │ /** A doc comment doesn't hide an unused attribute, nor does a nested ty + │ pe. */ + + Unused attribute: @as +This attribute has no effect here. +For example, some attributes are only meaningful in externals. + + + + Warning number 101 (configured as error) + /.../fixtures/warning_101_external_arg_attribute.res:6:34-36 + + 4 │ + 5 │ /** A doc comment doesn't hide an unused attribute, nor does a nested ty + │ pe. */ + 6 │ @send external third: (t, option<@as("z") int>) => unit = "third" + 7 │ + + Unused attribute: @as +This attribute has no effect here. +For example, some attributes are only meaningful in externals. \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/warning_101_floating_attribute.res.expected b/tests/build_tests/super_errors/expected/warning_101_floating_attribute.res.expected new file mode 100644 index 00000000000..6426642a4f8 --- /dev/null +++ b/tests/build_tests/super_errors/expected/warning_101_floating_attribute.res.expected @@ -0,0 +1,13 @@ + + Warning number 101 (configured as error) + /.../fixtures/warning_101_floating_attribute.res:2:32-34 + + 1 │ // A @@warning in the middle of a file applies to the externals after it + │ . + 2 │ @send external first: (string, @as("x") int) => unit = "first" + 3 │ + 4 │ @@warning("-101") + + Unused attribute: @as +This attribute has no effect here. +For example, some attributes are only meaningful in externals. \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/warning_101_recursive_module.res.expected b/tests/build_tests/super_errors/expected/warning_101_recursive_module.res.expected new file mode 100644 index 00000000000..cdf97622056 --- /dev/null +++ b/tests/build_tests/super_errors/expected/warning_101_recursive_module.res.expected @@ -0,0 +1,13 @@ + + Warning number 101 (configured as error) + /.../fixtures/warning_101_recursive_module.res:4:34-36 + + 2 │ // warnings, so the unused attribute is reported once. + 3 │ module rec M: { + 4 │ @module("./local") external f: @as("v") int => unit = "f" + 5 │ } = { + 6 │ @module("./local") external f: int => unit = "f" + + Unused attribute: @as +This attribute has no effect here. +For example, some attributes are only meaningful in externals. \ No newline at end of file diff --git a/tests/build_tests/super_errors/expected/warning_101_relative_module_external.res.expected b/tests/build_tests/super_errors/expected/warning_101_relative_module_external.res.expected new file mode 100644 index 00000000000..3bdee995822 --- /dev/null +++ b/tests/build_tests/super_errors/expected/warning_101_relative_module_external.res.expected @@ -0,0 +1,14 @@ + + Warning number 101 (configured as error) + /.../fixtures/warning_101_relative_module_external.res:4:39-41 + + 2 │ // don't inline it. Its unused attribute is reported once, and a @warnin + │ g on + 3 │ // the external applies to it. + 4 │ @module("./local") external relative: @as("v") int => unit = "relative" + 5 │ + 6 │ @warning("-101") @module("./local") + + Unused attribute: @as +This attribute has no effect here. +For example, some attributes are only meaningful in externals. \ No newline at end of file diff --git a/tests/build_tests/super_errors/fixtures/external_reserved_inline_primitive.res b/tests/build_tests/super_errors/fixtures/external_reserved_inline_primitive.res new file mode 100644 index 00000000000..0f1e593f1d6 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/external_reserved_inline_primitive.res @@ -0,0 +1,2 @@ +// This primitive name is only for @inline constants. +external answer: int = "#rescript-inline" diff --git a/tests/build_tests/super_errors/fixtures/warning_101_external_arg_attribute.res b/tests/build_tests/super_errors/fixtures/warning_101_external_arg_attribute.res new file mode 100644 index 00000000000..d101fd2555f --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/warning_101_external_arg_attribute.res @@ -0,0 +1,6 @@ +type t +@send external first: (t, @as("x") int) => unit = "first" +@send external second: (t, @as("y") int) => unit = "second" + +/** A doc comment doesn't hide an unused attribute, nor does a nested type. */ +@send external third: (t, option<@as("z") int>) => unit = "third" diff --git a/tests/build_tests/super_errors/fixtures/warning_101_floating_attribute.res b/tests/build_tests/super_errors/fixtures/warning_101_floating_attribute.res new file mode 100644 index 00000000000..6243bfb7ea8 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/warning_101_floating_attribute.res @@ -0,0 +1,6 @@ +// A @@warning in the middle of a file applies to the externals after it. +@send external first: (string, @as("x") int) => unit = "first" + +@@warning("-101") + +@send external second: (string, @as("y") int) => unit = "second" diff --git a/tests/build_tests/super_errors/fixtures/warning_101_recursive_module.res b/tests/build_tests/super_errors/fixtures/warning_101_recursive_module.res new file mode 100644 index 00000000000..f3bda5e1366 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/warning_101_recursive_module.res @@ -0,0 +1,7 @@ +// A recursive module's signature is typed twice, the first time without +// warnings, so the unused attribute is reported once. +module rec M: { + @module("./local") external f: @as("v") int => unit = "f" +} = { + @module("./local") external f: int => unit = "f" +} diff --git a/tests/build_tests/super_errors/fixtures/warning_101_relative_module_external.res b/tests/build_tests/super_errors/fixtures/warning_101_relative_module_external.res new file mode 100644 index 00000000000..44546d0ede6 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/warning_101_relative_module_external.res @@ -0,0 +1,7 @@ +// A relative @module external is exported as a value, so that other modules +// don't inline it. Its unused attribute is reported once, and a @warning on +// the external applies to it. +@module("./local") external relative: @as("v") int => unit = "relative" + +@warning("-101") @module("./local") +external silenced: @as("w") int => unit = "silenced" diff --git a/tests/ounit_tests/ounit_ast_mapper0_tests.ml b/tests/ounit_tests/ounit_ast_mapper0_tests.ml index 212a464e80e..d2c93c513ba 100644 --- a/tests/ounit_tests/ounit_ast_mapper0_tests.ml +++ b/tests/ounit_tests/ounit_ast_mapper0_tests.ml @@ -258,9 +258,7 @@ let test_fixed_argument_roundtrips_through_ast0 _ = ] int_type in - let vd = - Ast_helper.Val.mk ~prim:(Parsetree.Prim_name "f") (Location.mknoloc "f") typ - in + let vd = Ast_helper.Val.mk ~prim:"f" (Location.mknoloc "f") typ in let vd0 = Ast_mapper_to0.default_mapper.value_description Ast_mapper_to0.default_mapper vd @@ -320,7 +318,7 @@ let test_fixed_argument_locations_go_through_the_mapper _ = } in let vd = - Ast_helper.Val.mk ~prim:(Parsetree.Prim_name "f") (Location.mknoloc "f") + Ast_helper.Val.mk ~prim:"f" (Location.mknoloc "f") (Ast_helper.Typ.arrow ~loc [ fixed (Pfixed_json {txt = "{}"; loc = source_loc 6 8}); @@ -404,10 +402,7 @@ let test_fixed_argument_is_external_only _ = (match (roundtrip vd).pval_type.ptyp_desc with | Ptyp_arrow {params = [Parg_type _]} -> () | _ -> assert_failure "Expected an ordinary argument in a value declaration"); - match - (roundtrip {vd with pval_prim = Some (Parsetree.Prim_name "f")}).pval_type - .ptyp_desc - with + match (roundtrip {vd with pval_prim = Some "f"}).pval_type.ptyp_desc with | Ptyp_arrow {params = [Parg_fixed _]} -> () | _ -> assert_failure "Expected a fixed argument in an external" @@ -469,6 +464,32 @@ let test_try_finally_roundtrips_through_ast0 _ = OUnit.assert_equal finally.pexp_loc round_tripped_finally.pexp_loc | _ -> assert_failure "Expected a try with a finally after the v0 roundtrip" +let test_external_primitive_roundtrips_through_ast0 _ = + let typ = + Ast_helper.Typ.constr ~loc (Location.mknoloc (Longident.Lident "t")) [] + in + let external_ = + Ast_helper.Val.mk ~loc + ~attrs:[attr "send" (Parsetree.PStr [])] + ~prim:"join" (Location.mknoloc "join") typ + in + let wire = + Ast_mapper_to0.default_mapper.value_description + Ast_mapper_to0.default_mapper external_ + in + OUnit.assert_equal ["join"] wire.pval_prim; + OUnit.assert_bool "the FFI attribute stays on the wire" + (has_attr "send" wire.pval_attributes); + let round_tripped = + Ast_mapper_from0.default_mapper.value_description + Ast_mapper_from0.default_mapper wire + in + (match round_tripped.pval_prim with + | Some "join" -> () + | _ -> assert_failure "Expected the primitive string after the v0 roundtrip"); + OUnit.assert_bool "the FFI attribute survives the v0 roundtrip" + (has_attr "send" round_tripped.pval_attributes) + let test_v0_ternary_marker_preserves_other_attribute_order _ = let ident name = Ast_helper0.Exp.ident ~loc (Location.mknoloc (Longident.Lident name)) @@ -962,7 +983,7 @@ let test_jsx_component_on_value_descriptions_through_ast0 _ = attr "module" (Parsetree.PStr []); attr "react.component" (Parsetree.PStr []); ] - ~prim:(Prim_name "default") (Location.mknoloc "make") props_type + ~prim:"default" (Location.mknoloc "make") props_type in (match vd.pval_jsx_component with | Some {pjc_kind = Pjc_labelled None} -> () @@ -2876,6 +2897,8 @@ let suites = >:: test_record_rest_roundtrips_through_ast0; "ternary_roundtrips_through_ast0" >:: test_ternary_roundtrips_through_ast0; + "external_primitive_roundtrips_through_ast0" + >:: test_external_primitive_roundtrips_through_ast0; "v0_ternary_marker_preserves_other_attribute_order" >:: test_v0_ternary_marker_preserves_other_attribute_order; "v0_if_without_alternate_stays_if" diff --git a/tests/ounit_tests/ounit_string_literal_tests.ml b/tests/ounit_tests/ounit_string_literal_tests.ml index 2bc81e52ec4..a7b9e65df71 100644 --- a/tests/ounit_tests/ounit_string_literal_tests.ml +++ b/tests/ounit_tests/ounit_string_literal_tests.ml @@ -359,9 +359,13 @@ let assert_external_json_literal ~expected constant = | _ -> OUnit.assert_failure "expected a JavaScript JSON literal expression" let inline_string semantic = - match Ast_external_mk.inline_string semantic with - | Prim_inline_const constant -> constant - | _ -> OUnit.assert_failure "expected an inline constant" + match + Ast_external_mk.inline_const_of_expression + (Ast_helper.Exp.constant + (Pconst_string (String_literal.string_from_semantic semantic))) + with + | Some constant -> constant + | None -> OUnit.assert_failure "expected an inline constant" let assert_js_global ~expected (expression : J.expression) = match expression.expression_desc with diff --git a/tests/syntax_tests/data/ast-mapping/Externals.res b/tests/syntax_tests/data/ast-mapping/Externals.res new file mode 100644 index 00000000000..865d5d8f824 --- /dev/null +++ b/tests/syntax_tests/data/ast-mapping/Externals.res @@ -0,0 +1,11 @@ +// External declarations keep their primitive string and FFI attributes as +// written through the v0 compatibility AST; the type checker resolves them. +external identity: 'a => 'a = "%identity" +@val external parseInt: string => int = "parseInt" +@send external join: (array, string) => string = "join" +@module("./local") external local: int => int = "local" +@scope("Math") @val external max: (float, float) => float = "max" +@obj external makeProps: (~name: string, ~age: int=?, unit) => _ = "" +@send +external on: (t, @as("click") _, unit => unit) => unit = "addEventListener" +@variadic @module("path") external join2: array => string = "join" diff --git a/tests/syntax_tests/data/ast-mapping/expected/Externals.res.txt b/tests/syntax_tests/data/ast-mapping/expected/Externals.res.txt new file mode 100644 index 00000000000..a2702a3e498 --- /dev/null +++ b/tests/syntax_tests/data/ast-mapping/expected/Externals.res.txt @@ -0,0 +1,13 @@ +// External declarations keep their primitive string and FFI attributes as +// written through the v0 compatibility AST; the type checker resolves them. +external identity: 'a => 'a = "%identity" +@val external parseInt: string => int = "parseInt" +@send external join: (array, string) => string = "join" +@module("./local") external local: int => int = "local" +@scope("Math") @val external max: (float, float) => float = "max" +@obj external makeProps: (~name: string, ~age: int=?, unit) => _ = "" + +@send +external on: (t, @as("click") _, unit => unit) => unit = "addEventListener" + +@variadic @module("path") external join2: array => string = "join" diff --git a/tests/syntax_tests/data/oprint/expected/oprint.resi.txt b/tests/syntax_tests/data/oprint/expected/oprint.resi.txt index 83349c81af9..ae02cf96365 100644 --- a/tests/syntax_tests/data/oprint/expected/oprint.resi.txt +++ b/tests/syntax_tests/data/oprint/expected/oprint.resi.txt @@ -241,4 +241,8 @@ type call = CleanStart let f: (~a: int=?, unit) => int type opt = {x: int, y?: option} let secondOrder: (unit => 'a) => 'a -let thirdOrder: ((unit => unit) => 'a) => 'a \ No newline at end of file +let thirdOrder: ((unit => unit) => 'a) => 'a +@val external parseInt: string => int = "parseInt" +type el +@send external focus: el => unit = "focus" +let relative: int => int \ No newline at end of file diff --git a/tests/syntax_tests/data/oprint/oprint.res b/tests/syntax_tests/data/oprint/oprint.res index 06447df7b79..e217c1ff279 100644 --- a/tests/syntax_tests/data/oprint/oprint.res +++ b/tests/syntax_tests/data/oprint/oprint.res @@ -314,3 +314,8 @@ type opt = {x:int, y?: option} let secondOrder = f => f() let thirdOrder = f => f(() => ()) + +@val external parseInt: string => int = "parseInt" +type el +@send external focus: el => unit = "focus" +@module("./local") external relative: int => int = "relative" diff --git a/tests/syntax_tests/res_test.ml b/tests/syntax_tests/res_test.ml index 3635debfdb9..67dfd062c7f 100644 --- a/tests/syntax_tests/res_test.ml +++ b/tests/syntax_tests/res_test.ml @@ -658,6 +658,9 @@ let () = module Outcome_printer_tests = struct let signature_to_outcome structure = Lazy.force Res_outcome_printer.setup; + (* The type checker resolves externals through this hook, which the + compiler's drivers register in [Ppx_entry]. This test doesn't link it. *) + Primitive.resolve_external := Ast_external.resolve; Res_compmisc.init_path (); (Clflags.current ()).nopervasives := true; diff --git a/tests/tests/src/inline_const.mjs b/tests/tests/src/inline_const.mjs index 5c853d45450..467679a5280 100644 --- a/tests/tests/src/inline_const.mjs +++ b/tests/tests/src/inline_const.mjs @@ -27,12 +27,18 @@ let h = "hello"; let hh = "hellohello"; +let bigs = [ + 10n, + -3n +]; + export { x, N, N1, h, hh, + bigs, BigintConsts, } /* Not a pure module */ diff --git a/tests/tests/src/inline_const.res b/tests/tests/src/inline_const.res index ebbe2e15da2..d75b3fac1e9 100644 --- a/tests/tests/src/inline_const.res +++ b/tests/tests/src/inline_const.res @@ -38,6 +38,12 @@ let (a, b, c, d, e) = (f, f1, f2, f3, f4) @inline let f6 = 1 +@inline let big = 10n + +@inline let negBig = -3n + +let bigs = (big, negBig) + let () = Console.log((xx, xx0)) module BigintConsts = ( diff --git a/tests/tests/src/inline_const.resi b/tests/tests/src/inline_const.resi index 111d499a12e..6260a49e959 100644 --- a/tests/tests/src/inline_const.resi +++ b/tests/tests/src/inline_const.resi @@ -24,6 +24,12 @@ let hh: string @inline(1) let f6: int +@inline(10n) let big: bigint + +@inline(-3n) let negBig: bigint + +let bigs: (bigint, bigint) + module BigintConsts: ( X: { @inline(12n) let pos: bigint diff --git a/tests/tests/src/relative_path.mjs b/tests/tests/src/relative_path.mjs index 4083f38ea30..f7a211aa39f 100644 --- a/tests/tests/src/relative_path.mjs +++ b/tests/tests/src/relative_path.mjs @@ -1,6 +1,7 @@ // Generated by ReScript, PLEASE EDIT WITH CARE import * as FileJs from "./File.js"; +import * as Primitive_module from "@rescript/runtime/lib/es6/Primitive_module.mjs"; let foo = FileJs.foo; @@ -8,11 +9,74 @@ function foo2(prim) { return FileJs.foo2(prim); } +function nested(prim) { + return FileJs.nested(prim); +} + +let Nested = { + nested: nested +}; + +function Make(X) { + let inFunctor = prim => FileJs.inFunctor(prim); + let w = FileJs.inFunctor(X.v); + return { + inFunctor: inFunctor, + w: w + }; +} + +let Recursive = Primitive_module.init([ + "relative_path.res", + 27, + 4 +], { + TAG: "Module", + _0: [ + [ + "Function", + "inRec" + ], + [ + "Function", + "call" + ] + ] +}); + +function inRec(prim) { + return FileJs.inRec(prim); +} + +function call(x) { + return FileJs.inRec(x); +} + +Primitive_module.update({ + TAG: "Module", + _0: [ + [ + "Function", + "inRec" + ], + [ + "Function", + "call" + ] + ] +}, Recursive, { + inRec: inRec, + call: call +}); + let bar = foo; export { foo, foo2, bar, + Nested, + Make, + Recursive, } /* foo Not a pure module */ diff --git a/tests/tests/src/relative_path.res b/tests/tests/src/relative_path.res index 9d3ed00e5f8..ca69cc55a81 100644 --- a/tests/tests/src/relative_path.res +++ b/tests/tests/src/relative_path.res @@ -5,3 +5,26 @@ @module("./File.js") external foo2: int => int = "foo2" let bar = foo + +module Nested = { + @module("./File.js") external nested: int => int = "nested" +} + +module Make = ( + X: { + let v: int + }, +) => { + @module("./File.js") external inFunctor: int => int = "inFunctor" + let w = inFunctor(X.v) +} + +@module("pkg") external notRelative: int => int = "notRelative" + +module rec Recursive: { + @module("./File.js") external inRec: int => int = "inRec" + let call: int => int +} = { + @module("./File.js") external inRec: int => int = "inRec" + let call = x => inRec(x) +} diff --git a/tests/tests/src/relative_path_intf.mjs b/tests/tests/src/relative_path_intf.mjs new file mode 100644 index 00000000000..7ecb37cdd1c --- /dev/null +++ b/tests/tests/src/relative_path_intf.mjs @@ -0,0 +1,17 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as FileJs from "./File.js"; + +function declared(prim) { + return FileJs.declared(prim); +} + +function asValue(prim) { + return FileJs.asValue(prim); +} + +export { + declared, + asValue, +} +/* ./File.js Not a pure module */ diff --git a/tests/tests/src/relative_path_intf.res b/tests/tests/src/relative_path_intf.res new file mode 100644 index 00000000000..a66d78ca28d --- /dev/null +++ b/tests/tests/src/relative_path_intf.res @@ -0,0 +1,2 @@ +@module("./File.js") external declared: int => int = "declared" +@module("./File.js") external asValue: int => int = "asValue" diff --git a/tests/tests/src/relative_path_intf.resi b/tests/tests/src/relative_path_intf.resi new file mode 100644 index 00000000000..0d1f58066e6 --- /dev/null +++ b/tests/tests/src/relative_path_intf.resi @@ -0,0 +1,2 @@ +@module("./File.js") external declared: int => int = "declared" +let asValue: int => int diff --git a/tests/tests/src/relative_path_use.mjs b/tests/tests/src/relative_path_use.mjs new file mode 100644 index 00000000000..5888c4e27c9 --- /dev/null +++ b/tests/tests/src/relative_path_use.mjs @@ -0,0 +1,35 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Pkg from "pkg"; +import * as Relative_path from "./relative_path.mjs"; +import * as Relative_path_intf from "./relative_path_intf.mjs"; + +let a = Relative_path.foo2(1); + +let b = Relative_path.Nested.nested(2); + +let d = Pkg.notRelative(3); + +let M = Relative_path.Make({ + v: 4 +}); + +let e = Relative_path_intf.declared(5); + +let f = Relative_path_intf.asValue(6); + +let g = Relative_path.Recursive.inRec(7); + +let c = Relative_path.bar; + +export { + a, + b, + c, + d, + M, + e, + f, + g, +} +/* a Not a pure module */ diff --git a/tests/tests/src/relative_path_use.res b/tests/tests/src/relative_path_use.res new file mode 100644 index 00000000000..0e57c84a356 --- /dev/null +++ b/tests/tests/src/relative_path_use.res @@ -0,0 +1,15 @@ +// Other modules call an external with a relative path through the value its +// module exports, since the path is relative to that module's file. Only the +// non-relative external is inlined. +let a = Relative_path.foo2(1) +let b = Relative_path.Nested.nested(2) +let c = Relative_path.bar +let d = Relative_path.notRelative(3) + +module M = Relative_path.Make({ + let v = 4 +}) + +let e = Relative_path_intf.declared(5) +let f = Relative_path_intf.asValue(6) +let g = Relative_path.Recursive.inRec(7)