From ad393f31f573d2ae2594ef611fb29a69cb2e4e86 Mon Sep 17 00:00:00 2001 From: Cristiano Calcagno Date: Tue, 24 Nov 2026 04:22:49 +0100 Subject: [PATCH 1/6] Print TypeScript for a module under the experimental -bs-emit-ts flag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: A feasibility study for checking ReScript output with TScert, which reads TypeScript whose top-level functions annotate their parameters and result. The flag writes `.res.ts` (`.mts` for `.mjs`, `.cts` for `.cjs`) in place of the JavaScript output, annotates each top-level function from the typed tree, puts the module's type declarations at the top through genType's translation, and prints nested options by depth and polymorphic option functions as overloads so both `tsc --strict` and TScert accept them. `Js_ts_annot` in `compiler/backend` holds the per-request annotation table keyed by `Ident.t` (name and stamp) that the JS printer reads; `Js_ts_collect` in `compiler/driver` populates it from the typed tree using `gentype`, keeping `backend` free of a `gentype` dependency. `RESCRIPT_EMIT_TS_DEBUG=1` reports, per printed top-level function, whether its stamp and its parameters' stamps are the typed tree's. JS modified (top-level functions and exports under -bs-emit-ts): Example: type point = {x: int, y: int, label: string} let moveX = (p: point, dx: int) => {...p, x: p.x + dx} Before (js): function moveX(p, dx) { return { x: p.x + dx | 0, y: p.y, label: p.label }; } export { moveX, } After (js): Rec.res.ts export type point = { readonly x: number; readonly y: number; readonly label: string }; export function moveX(p: point, dx: number): point { return { x: p.x + dx | 0, y: p.y, label: p.label }; } JS modified (-bs-emit-ts type parameters, optional arguments and lone return;): Example: let second = (_x: 'a, y: 'b): 'b => y let scale = (x: int, ~by=2) => x * by let offset = (~from=0, x: int) => x - from let none = (): option => None Before (js): function second(_x, y) { return y; } function scale(x, byOpt) { … } function offset(fromOpt, x) { … } function none() { } After (js): export function second(_x: a, y: b): b { return y; } export function scale(x: number, byOpt?: number): number { … } export function offset(fromOpt: (undefined | number), x: number): number { … } export function none(): (undefined | number) { return; } Representation modified (option under -bs-emit-ts): After (representation): option ↦ undefined | number option> ↦ undefined | number | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 } option>> ↦ undefined | number | { …: 0 } | { …: 1 } option ↦ undefined | void | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 } option<'a> in a type declaration, or at an abstract payload ↦ undefined | a | { …: number } option> (payload may own marker key) ↦ undefined | keyed | { …: number } rule: Some(v) is the marker of depth 0 when v is undefined, of depth d + 1 when v is the marker of depth d, and v otherwise (Primitive_option.some); a payload is no marker only where it cannot hold undefined and may own no key BS_PRIVATE_NESTED_SOME_NONE JS modified (-bs-emit-ts polymorphic option code): Example: let getOr = (o: option<'a>, d: 'a) => switch o { | Some(v) => v | None => d } After (js): export function getOr(o: (undefined | a), d: a): a; export function getOr(o: (undefined | ( (undefined | a) | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a); export function getOr(o: (undefined | ( (undefined | a) | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a) { … } Review: Does JavaScript or genType output change outside -bs-emit-ts? No: all printer hooks and the lone `return;` guard are gated on `emit_ts`, and genType's `option_payload_markers` hook defaults to `No_markers`; the genType test suites produce unchanged outputs. Review: Why split `Js_ts_annot` (`backend`) and `Js_ts_collect` (`driver`)? `compiler/backend` does not depend on `gentype`, whereas `compiler/driver` already links both `backend` and `gentype`. Keeping the per-request table in `backend` and the typed-tree/genType collector in `driver` preserves that boundary. Review: Why overloads instead of a conditional type for `Some`? `Some` at an unbounded `A` is true only if no value but the runtime's markers owns the key `BS_PRIVATE_NESTED_SOME_NONE`; a TypeScript object type admits further keys. Each overload is the function's signature at `'a := option^k` (`k = 0, 1`) with `a` bounded to primitives, holding with no extra assumption. Signed-off-by: Cristiano Calcagno --- compiler/backend/js_dump.ml | 84 +++- compiler/backend/js_dump_import_export.ml | 4 + compiler/backend/js_dump_program.ml | 8 + compiler/backend/js_ts_annot.ml | 128 +++++ compiler/backend/lam_compile_main.ml | 4 + compiler/driver/dune | 1 + compiler/driver/js_implementation.ml | 26 +- compiler/driver/js_ts_collect.ml | 446 ++++++++++++++++++ compiler/driver/rescript_compiler_driver.ml | 5 + compiler/gentype/gentype_config.ml | 15 + compiler/gentype/translate_core_type.ml | 60 ++- .../gentype/translate_type_expr_from_types.ml | 49 ++ compiler/typing/js_config.ml | 2 + compiler/typing/js_config.mli | 3 + 14 files changed, 786 insertions(+), 49 deletions(-) create mode 100644 compiler/backend/js_ts_annot.ml create mode 100644 compiler/driver/js_ts_collect.ml diff --git a/compiler/backend/js_dump.ml b/compiler/backend/js_dump.ml index 5a9e2bc6ca1..b4dd3795a5a 100644 --- a/compiler/backend/js_dump.ml +++ b/compiler/backend/js_dump.ml @@ -328,6 +328,21 @@ and record_rest_pattern cxt f fields rest = and formal_parameter_list cxt f l = iter_lst cxt f l Ext_pp_scope.ident comma_sp +(* [-bs-emit-ts]: each parameter followed by its type, where the typed tree + gave one to this identifier. *) +and annotated_parameter_list cxt f l = + iter_lst cxt f l + (fun cxt f id -> + let cxt = Ext_pp_scope.ident cxt f id in + (match Js_ts_annot.param_type id with + | Some {ty; optional} -> + P.string f (if optional then "?:" else ":"); + P.space f; + P.string f ty + | None -> ()); + cxt) + comma_sp + (* IdentMap *) (* f/122 --> @@ -455,12 +470,31 @@ let rec pp_function ~return_unit ~async ~is_method ?directive cxt (f : P.t) in function_body ~return_unit cxt f b)) else + let ts_top = + match fn_state with + | Name_top x when Js_ts_annot.enabled () -> + Js_ts_annot.report_function x l; + Some x + | _ -> None + in let cxt = - match l with - | [single] when arrow -> Ext_pp_scope.ident inner_cxt f single - | l -> + match (l, ts_top) with + | l, Some x -> + P.string f (Js_ts_annot.type_params x); + P.paren_group f 1 (fun _ -> annotated_parameter_list inner_cxt f l) + | [single], None when arrow -> Ext_pp_scope.ident inner_cxt f single + | l, None -> P.paren_group f 1 (fun _ -> formal_parameter_list inner_cxt f l) in + (match ts_top with + | Some x -> ( + match Js_ts_annot.result_type x with + | Some ty -> + P.string f ":"; + P.space f; + P.string f ty + | None -> ()) + | None -> ()); P.space f; if arrow then ( P.string f L.arrow; @@ -494,6 +528,42 @@ let rec pp_function ~return_unit ~async ~is_method ?directive cxt (f : P.t) param_body (); semi f | Name_top x -> + let export = Js_ts_annot.export_inline x in + (* [-bs-emit-ts]: the function's overloads, each a declaration + without a body before the function, which carries its own + signature. An overload takes no [async]. *) + if Js_ts_annot.enabled () then + List.iter + (fun (typed, result) -> + if export then ( + P.string f L.export; + P.space f); + P.string f (L.function_ ~async:false ~arrow:false); + ignore (Ext_pp_scope.ident inner_cxt f x : cxt); + P.string f (Js_ts_annot.type_params x); + ignore + (P.paren_group f 1 (fun _ -> + iter_lst inner_cxt f l + (fun cxt f id -> + let cxt = Ext_pp_scope.ident cxt f id in + (match Js_ts_annot.overload_param_type typed id with + | Some ty -> + P.string f ":"; + P.space f; + P.string f ty + | None -> ()); + cxt) + comma_sp) + : cxt); + P.string f ":"; + P.space f; + P.string f result; + semi f; + P.newline f) + (Js_ts_annot.overloads x); + if export then ( + P.string f L.export; + P.space f); P.string f (L.function_ ~async ~arrow); ignore (Ext_pp_scope.ident inner_cxt f x : cxt); param_body () @@ -1604,7 +1674,13 @@ and function_body ?directive (cxt : cxt) f ~return_unit (b : J.block) : unit = ignore (statement false cxt f {s with statement_desc = If (bool, then_, [])} : cxt) - | Return {expression_desc = Undefined _} -> () + (* A function whose body is only [return;] prints an empty body, except + under [-bs-emit-ts]: TypeScript requires a [return] in a function + whose declared result type is other than [undefined], [void] or + [any]. *) + | Return {expression_desc = Undefined _} when not (Js_ts_annot.enabled ()) + -> + () | Return exp when return_unit -> ignore (statement false cxt f (S.exp exp) : cxt) | _ -> ignore (statement false cxt f s : cxt)) diff --git a/compiler/backend/js_dump_import_export.ml b/compiler/backend/js_dump_import_export.ml index 32e328e818c..29c3271a443 100644 --- a/compiler/backend/js_dump_import_export.ml +++ b/compiler/backend/js_dump_import_export.ml @@ -81,6 +81,10 @@ let exports cxt f (idents : Ident.t list) = (** Print module in ESModule format, it is ESModule, trailing comma is valid ES code *) let esmodule_export cxt f (idents : Ident.t list) = P.at_least_two_lines f; + (* [-bs-emit-ts]: functions printed as [export function] leave the list *) + let idents = + List.filter (fun id -> not (Js_ts_annot.exported_inline id)) idents + in match idents with | [] -> cxt | _ -> diff --git a/compiler/backend/js_dump_program.ml b/compiler/backend/js_dump_program.ml index af1d1d04d10..114595ae622 100644 --- a/compiler/backend/js_dump_program.ml +++ b/compiler/backend/js_dump_program.ml @@ -124,6 +124,14 @@ let esmodule_program ~output_dir fmt f (x : J.deps_program) = x.modules) in let () = P.at_least_two_lines f in + Js_ts_annot.set_exports x.program.exports; + (if Js_ts_annot.enabled () then + match Js_ts_annot.header () with + | "" -> () + | header -> + P.string f header; + P.newline f; + P.at_least_two_lines f); let cxt = Js_dump.statements true cxt f x.program.block in Js_dump_import_export.esmodule_export cxt f x.program.exports diff --git a/compiler/backend/js_ts_annot.ml b/compiler/backend/js_ts_annot.ml new file mode 100644 index 00000000000..4147766b206 --- /dev/null +++ b/compiler/backend/js_ts_annot.ml @@ -0,0 +1,128 @@ +(* Experimental TypeScript emission ([-bs-emit-ts]): per-request annotation + table populated by [Js_ts_collect] in the driver and read by the JS + printer in the backend. + + The typed tree gives each top-level function's parameters and result a + [Types.type_expr]; genType's translation turns each into TypeScript. The + printer looks the parameters and the function up by their [Ident.t] + (name and stamp), so an annotation reaches the output only when the + identifier the J IR prints is the one the typed tree bound. *) + +type key = string * int + +type param = { + ty: string; + optional: bool; + (** printed [p?: ty]: an optional labelled argument followed only by + optional labelled arguments, with [ty] the option's element type *) +} + +type state = { + params: (key, param) Hashtbl.t; (** parameter ident -> its annotation *) + results: (key, string) Hashtbl.t; (** top-level function -> result type *) + generics: (key, string list) Hashtbl.t; + (** top-level function -> its type parameters, in order of occurrence, + each with its bound if it has one *) + overloads: (key, ((key * string) list * string) list) Hashtbl.t; + (** top-level function -> its overloads, each its parameters' types by + their idents and its result type *) + names: (string, int) Hashtbl.t; + (** top-level function name -> its stamp, to report lost stamps *) + mutable header: string; (** the module's type declarations *) + mutable exports: Ident.t list; (** the program's exports *) + inline_exports: (key, unit) Hashtbl.t; + (** exports printed as [export function] *) +} + +let fresh () = + { + params = Hashtbl.create 16; + results = Hashtbl.create 16; + generics = Hashtbl.create 16; + overloads = Hashtbl.create 16; + names = Hashtbl.create 16; + header = ""; + exports = []; + inline_exports = Hashtbl.create 16; + } + +let key = Request_local.new_key fresh +let current () = Domain.DLS.get key +let enabled () = !((Js_config.current ()).emit_ts) +let key_of (id : Ident.t) : key = (id.name, id.stamp) + +(* [.res.js] -> [.res.ts], [.mjs] -> [.mts], [.cjs] -> [.cts] *) +let ts_suffix suffix = + if Filename.check_suffix suffix ".mjs" then + Filename.chop_suffix suffix ".mjs" ^ ".mts" + else if Filename.check_suffix suffix ".cjs" then + Filename.chop_suffix suffix ".cjs" ^ ".cts" + else if Filename.check_suffix suffix ".js" then + Filename.chop_suffix suffix ".js" ^ ".ts" + else suffix ^ ".ts" + +let debug = Sys.getenv_opt "RESCRIPT_EMIT_TS_DEBUG" <> None + +let header () = (current ()).header + +(* A top-level function's overloads: each its parameters' types by their + idents and its result type. *) +let overloads (id : Ident.t) = + match Hashtbl.find_opt (current ()).overloads (key_of id) with + | Some overloads -> overloads + | None -> [] + +let overload_param_type typed (id : Ident.t) = List.assoc_opt (key_of id) typed + +(* Report, once per top-level function the printer names, whether its stamp + and its parameters' stamps are the typed tree's. *) +let report_function (id : Ident.t) (params : Ident.t list) = + if debug then + let st = current () in + let fn = + if Hashtbl.mem st.results (key_of id) then "stamp kept" + else + match Hashtbl.find_opt st.names id.name with + | Some s -> Printf.sprintf "stamp lost (typed %d, J %d)" s id.stamp + | None -> "not a typed top-level function" + in + let ps = + List.map + (fun p -> + Printf.sprintf "%s/%d:%s" p.Ident.name p.stamp + (if Hashtbl.mem st.params (key_of p) then "kept" else "lost")) + params + in + Printf.eprintf "emit-ts: %s/%d %s; params %s\n" id.name id.stamp fn + (String.concat ", " ps) + +let param_type (id : Ident.t) = Hashtbl.find_opt (current ()).params (key_of id) + +let result_type (id : Ident.t) = + Hashtbl.find_opt (current ()).results (key_of id) + +let type_params (id : Ident.t) = + match Hashtbl.find_opt (current ()).generics (key_of id) with + | Some vars -> "<" ^ String.concat ", " vars ^ ">" + | None -> "" + +let set_exports exports = + let st = current () in + st.exports <- exports; + Hashtbl.reset st.inline_exports + +(* A top-level function is printed [export function f] when it is exported + under its own name. The printer is assumed to print a top-level function + under its source name. *) +let export_inline (id : Ident.t) = + enabled () + && + let st = current () in + List.exists (fun e -> Ident.same e id) st.exports + && Ext_ident.convert id.name = id.name + && + (Hashtbl.replace st.inline_exports (key_of id) (); + true) + +let exported_inline (id : Ident.t) = + enabled () && Hashtbl.mem (current ()).inline_exports (key_of id) diff --git a/compiler/backend/lam_compile_main.ml b/compiler/backend/lam_compile_main.ml index 244696bf577..8a8c12a5eda 100644 --- a/compiler/backend/lam_compile_main.ml +++ b/compiler/backend/lam_compile_main.ml @@ -537,6 +537,10 @@ let lambda_as_module (lambda_output : J.deps_program) (output_prefix : string) : (Compiler_request_output.stdout_channel ()) else Js_packages_info.iter package_info (fun {module_system; path; suffix} -> + let suffix = + if !((Js_config.current ()).emit_ts) then Js_ts_annot.ts_suffix suffix + else suffix + in let basename = Ext_namespace.change_ext_ns_suffix (Filename.basename output_prefix) diff --git a/compiler/driver/dune b/compiler/driver/dune index b70ca04fe41..b021f5fc4a2 100644 --- a/compiler/driver/dune +++ b/compiler/driver/dune @@ -28,6 +28,7 @@ rescript_compiler_driver rescript_compiler_build_identity js_implementation + js_ts_collect ext_file_extensions) (instrumentation (backend bisect_ppx)) diff --git a/compiler/driver/js_implementation.ml b/compiler/driver/js_implementation.ml index 00bc299347f..a308a5d1874 100644 --- a/compiler/driver/js_implementation.ml +++ b/compiler/driver/js_implementation.ml @@ -137,19 +137,19 @@ let after_parsing_impl ppf outputprefix (ast : Parsetree.structure) = let typedtree_coercion = (typedtree, coercion) in print_if ppf (Clflags.current ()).dump_typedtree Printtyped.implementation_with_coercion typedtree_coercion; - (if !((Js_config.current ()).cmi_only) then Warnings.check_fatal () - else - let implementation = - Translmod.transl_implementation modulename finalenv signature - typedtree_coercion - in - print_if ppf (Clflags.current ()).dump_rawlambda Printlambda.lambda - implementation.lambda; - let js_program = - Lam_compile_main.compile outputprefix implementation - in - if not !((Js_config.current ()).cmj_only) then - Lam_compile_main.lambda_as_module js_program outputprefix); + if !((Js_config.current ()).cmi_only) then Warnings.check_fatal () + else ( + if !((Js_config.current ()).emit_ts) then + Js_ts_collect.collect ~module_name:modulename typedtree; + let implementation = + Translmod.transl_implementation modulename finalenv signature + typedtree_coercion + in + print_if ppf (Clflags.current ()).dump_rawlambda Printlambda.lambda + implementation.lambda; + let js_program = Lam_compile_main.compile outputprefix implementation in + if not !((Js_config.current ()).cmj_only) then + Lam_compile_main.lambda_as_module js_program outputprefix); process_with_gentype (outputprefix ^ ".cmt")) let implementation ~parser ppf fname = diff --git a/compiler/driver/js_ts_collect.ml b/compiler/driver/js_ts_collect.ml new file mode 100644 index 00000000000..979b706efd7 --- /dev/null +++ b/compiler/driver/js_ts_collect.ml @@ -0,0 +1,446 @@ +(* Experimental TypeScript emission ([-bs-emit-ts]): collect top-level + function annotations and module type declarations from the typed tree + using genType's translation, storing them in [Js_ts_annot]. *) + +let config () = {Gentype_config.default with everything = true} + +(* [option] holds [undefined] for [None], and for [Some(v)] the value + [Primitive_option.some(v)]: the frozen marker + [{BS_PRIVATE_NESTED_SOME_NONE: 0}] when [v] is [undefined], the marker of + depth [d + 1] when [v] is the marker of depth [d], and [v] itself + otherwise. The compiler wraps and unwraps with the identity where the + payload type cannot hold [undefined] + ([Typeopt.type_cannot_contain_undefined]); there [option] prints + [undefined | t]. Elsewhere it prints [t] beside the marker of each depth + [Some(v)] can be, read off the encoding of [t]: + - the values of [option] are [undefined] and [Some(v)] for [v] in [u]; + - the value of [unit] is [undefined]; + - a value of a type that cannot hold [undefined] and owns no field + [BS_PRIVATE_NESTED_SOME_NONE] is no marker either; a record or an + inline record naming that field at run time ([@as]), or an object type, + may hold any depth there, which [Primitive_option.some] reads. + The depth of a marker is a literal type where the encoding is known, and + [number] elsewhere: at an abstract type, at a type that may own the key, + and at a type declaration's parameter. A function's type parameter that + is an option's payload is bounded instead (below), so its values are + neither [undefined] nor markers. *) +type encoding = + | Known of {undefined: bool; markers: int list} + (** whether a value can be [undefined], and the depths of the markers + it can be *) + | Unknown + +let some_markers ~undefined ~markers = + (if undefined then [0] else []) @ List.map succ markers + +let marker_key = "BS_PRIVATE_NESTED_SOME_NONE" + +(* Whether a value of [t] may own the marker key: a record or an inline + record with a field of that runtime name, an object type, or a variant + case's payload that may; a declaration not found may. *) +let rec may_own_marker_key ~env ~visiting (t : Types.type_expr) = + let owns (labels : Types.label_declaration list) = + List.exists (fun l -> Record_runtime.declaration_name l = marker_key) labels + in + match (Ctype.expand_head_opt env t).desc with + | Tobject _ -> true + | Tconstr (path, _, _) when List.exists (Path.same path) visiting -> false + | Tconstr (path, _, _) -> ( + match Env.find_type path env with + | {type_kind = Type_record (labels, _)} -> owns labels + | {type_kind = Type_variant (cases, _)} -> + let visiting = path :: visiting in + List.exists + (fun (c : Types.constructor_declaration) -> + match c.cd_args with + | Cstr_record labels -> owns labels + | Cstr_tuple args -> + List.exists (may_own_marker_key ~env ~visiting) args) + cases + | _ -> false + | exception Not_found -> true) + | _ -> false + +let rec encoding ~env ~var (t : Types.type_expr) = + match (Ctype.expand_head_opt env t).desc with + | Tconstr (path, [u], _) when Path.same path Predef.path_option -> ( + match encoding ~env ~var u with + | Known {undefined; markers} -> + Known {undefined = true; markers = some_markers ~undefined ~markers} + | Unknown -> Unknown) + | Tconstr (path, [], _) when Path.same path Predef.path_unit -> + Known {undefined = true; markers = []} + | Tvar _ -> var t + | _ -> + if + Typeopt.type_cannot_contain_undefined t env + && not (may_own_marker_key ~env ~visiting:[] t) + then Known {undefined = false; markers = []} + else Unknown + +(* The markers [option] can hold at the payload [t]; [var] gives the + encoding of a type variable. *) +let payload_markers ~env ~var (t : Types.type_expr) : + Gentype_config.option_markers = + match encoding ~env ~var t with + | Known {undefined; markers} -> ( + match some_markers ~undefined ~markers with + | [] -> No_markers + | depths -> Depths depths) + | Unknown -> Any_depth + +(* A type declaration's parameter: any value, a marker of any depth among + them. *) +let declaration_var _ = Unknown + +(* The bound of a function's type parameter that is an option's payload: the + types none of whose values is [undefined] or a marker, so that + [Primitive_option.some] and [valFromOption] return such a value unchanged + and [option] is exactly [undefined | a]. A primitive owns no key + [BS_PRIVATE_NESTED_SOME_NONE], and its prototypes hold none. A record type + does not exclude the key: TypeScript's object types admit further keys. *) +let payload_bound = "string | number | boolean | bigint" + +(* The deepest nesting a function's overloads state for each bounded type + parameter (below): [a], [option], ..., [option^n]. *) +let overload_depth = 1 + +(* The type variables that are the payload of an option in [t]. *) +let rec payload_vars (t : Gentype_common.type_) = + match t with + | Option (TypeVar v) -> [v] + | Array (t, _) | Dict t | Null t | Nullable t | Option t | Promise t -> + payload_vars t + | Function {arg_types; ret_type} -> + List.concat_map + (fun (a : Gentype_common.arg_type) -> payload_vars a.a_type) + arg_types + @ payload_vars ret_type + | Ident {type_args} -> List.concat_map payload_vars type_args + | Object (_, fields) -> + List.concat_map + (fun (f : Gentype_common.field) -> + match (f.optional, f.type_) with + | Optional, TypeVar v -> [v] + | _ -> payload_vars f.type_) + fields + | Tuple ts -> List.concat_map payload_vars ts + | TypeVar _ -> [] + | Variant {inherits; payloads} -> + List.concat_map payload_vars inherits + @ List.concat_map + (fun (p : Gentype_common.payload) -> payload_vars p.t) + payloads + +let type_to_string type_ = + Emit_type.type_to_string ~config:(config ()) + ~type_name_is_interface:(fun _ -> false) + type_ + +(* The types of one function's parameters and result, translated with one + namer for anonymous type variables, so a variable shared between them gets + one name. Also the type variables, in order of first occurrence. *) +let ts_of_signature ~env ~var type_env (type_exprs : Types.type_expr list) = + let config = + {(config ()) with option_payload_markers = payload_markers ~env ~var} + in + let translations = + Translate_type_expr_from_types.translate_type_exprs_from_types ~config + ~type_env type_exprs + in + let type_vars = + List.fold_left + (fun acc (t : Translate_type_expr_from_types.translation) -> + List.fold_left + (fun acc v -> if List.mem v acc then acc else acc @ [v]) + acc (Type_vars.free t.type_)) + [] translations + in + ( List.map + (fun (t : Translate_type_expr_from_types.translation) -> + type_to_string t.type_) + translations, + type_vars, + List.map + (fun (t : Translate_type_expr_from_types.translation) -> t.type_) + translations ) + +let is_optional (p : Typedtree.function_param) = + match p.fp_lbl with + | Optional _ -> true + | Nolabel | Labelled _ -> false + +(* The element type of [option]. *) +let option_element (t : Types.type_expr) = + match (Ctype.repr t).desc with + | Tconstr (path, [elt], _) when Path.same path Predef.path_option -> Some elt + | _ -> None + +(* The parameters printed [p?: t]: the optional labelled arguments after the + last mandatory one, because TypeScript requires every parameter after an + optional one to be optional, whose element type [t] holds no marker. An + optional argument earlier in the list prints [p: undefined | t]; a call + from ReScript passes [undefined] for an omitted argument in either + position. *) +let rec trailing_optionals ~env ~var (params : Typedtree.function_param list) = + match params with + | [] -> ([], true) + | p :: rest -> + let flags, all_optional = trailing_optionals ~env ~var rest in + let optional = + all_optional && is_optional p + && + match option_element p.fp_pat.pat_type with + | Some elt -> payload_markers ~env ~var elt = No_markers + | None -> false + in + (optional :: flags, optional) + +(* A signature's types with type variables replaced, through type + constructors, arrows and tuples; any other type naming a replaced variable + has no such copy here. *) +exception Unsubstitutable + +let mentions vars (t : Types.type_expr) = + let visited = ref [] in + let rec go (t : Types.type_expr) = + let t = Ctype.repr t in + if not (List.memq t !visited) then ( + visited := t :: !visited; + if List.memq t vars then raise Exit; + Btype.iter_type_expr go t) + in + match go t with + | () -> false + | exception Exit -> true + +let substitute pairs (t : Types.type_expr) = + let rec go visiting (t : Types.type_expr) = + let t = Ctype.repr t in + match List.assq_opt t pairs with + | Some r -> r + | None -> ( + if List.memq t visiting then raise Unsubstitutable; + let visiting = t :: visiting in + match t.desc with + | Tconstr (p, args, _) -> + Btype.newgenty + (Tconstr (p, List.map (go visiting) args, ref Types.Mnil)) + | Tarrow (params, ret) -> + Btype.newgenty + (Tarrow + ( List.map + (fun (a : Types.arg) -> {a with typ = go visiting a.typ}) + params, + go visiting ret )) + | Ttuple ts -> Btype.newgenty (Ttuple (List.map (go visiting) ts)) + | _ -> + if mentions (List.map fst pairs) t then raise Unsubstitutable else t) + in + go [] t + +(* [option^depth] *) +let rec nested depth (t : Types.type_expr) = + if depth = 0 then t + else + Btype.newgenty + (Tconstr (Predef.path_option, [nested (depth - 1) t], ref Types.Mnil)) + +(* Every assignment of a depth from [0] to [overload_depth] to each of [n] + variables, the shallowest first. *) +let rec depth_assignments n = + if n = 0 then [[]] + else + List.concat_map + (fun rest -> List.init (overload_depth + 1) (fun d -> d :: rest)) + (depth_assignments (n - 1)) + +(* A function whose type parameter is an option's payload is printed with + one overload per nesting of that parameter, [a], [option], up to + [overload_depth] options, each the function's signature at that instance + with [a] bounded as above: each holds of the function's code, which is + the code of every instance. Its own signature, which no caller sees, is + the deepest instance's, whose parameters admit every overload's. An + optional argument then prints [p: undefined | t], one form for every + overload. *) +let collect_function (st : Js_ts_annot.state) type_env (id : Ident.t) + (e : Typedtree.expression) = + match e.exp_desc with + | Texp_function {params; body} -> + Hashtbl.replace st.names id.name id.stamp; + let env = e.exp_env in + (* The type variables an option's encoding reaches: each is bounded. *) + let reached = ref [] in + let var t = + let t = Ctype.repr t in + if not (List.memq t !reached) then reached := !reached @ [t]; + Known {undefined = false; markers = []} + in + let signature optionals = + List.map2 + (fun (p : Typedtree.function_param) optional -> + match option_element p.fp_pat.pat_type with + | Some elt when optional -> elt + | _ -> p.fp_pat.pat_type) + params optionals + @ [body.exp_type] + in + let optionals, _ = trailing_optionals ~env ~var params in + let _ = ts_of_signature ~env ~var type_env (signature optionals) in + let payload = !reached in + let optionals = + if payload = [] then optionals else List.map (fun _ -> false) optionals + in + let base = signature optionals in + (* Every type variable of the signature, each with its name. *) + let vars = + List.fold_left + (fun acc t -> + List.fold_left + (fun acc v -> + let v = Ctype.repr v in + if List.memq v acc then acc else acc @ [v]) + acc (Ctype.free_variables t)) + [] base + in + let strings, type_vars, translated = + ts_of_signature ~env ~var type_env (base @ vars) + in + let arity = List.length base in + let types = List.filteri (fun i _ -> i < arity) strings in + let translated_signature = List.filteri (fun i _ -> i < arity) translated in + let names = + List.filteri (fun i _ -> i >= arity) translated + |> List.map (fun (t : Gentype_common.type_) -> + match t with + | TypeVar v -> v + | _ -> assert false) + in + let named = List.combine vars names in + let bounded = + List.filter_map (fun v -> List.assq_opt v named) payload + @ List.concat + (List.map2 + (fun optional (t : Gentype_common.type_) -> + match (optional, t) with + | true, TypeVar v -> [v] + | _ -> payload_vars t) + (optionals @ [false]) translated_signature) + in + if type_vars <> [] then + Hashtbl.replace st.generics (Js_ts_annot.key_of id) + (List.map + (fun v -> + if List.mem v bounded then v ^ " extends " ^ payload_bound else v) + type_vars); + let at_depths depths = + let pairs = + List.map + (fun (v, name) -> + let fresh = Btype.newgenty (Tvar (Some name)) in + match List.assq_opt v (List.combine payload depths) with + | Some d -> (v, nested d fresh) + | None -> (v, fresh)) + named + in + let strings, _, _ = + ts_of_signature ~env ~var type_env (List.map (substitute pairs) base) + in + strings + in + let types = + if payload = [] then types + else + match + ( List.map at_depths (depth_assignments (List.length payload)), + at_depths (List.map (fun _ -> overload_depth) payload) ) + with + | overloads, deepest -> + Hashtbl.replace st.overloads (Js_ts_annot.key_of id) + (List.map + (fun strings -> + let rec split params strings = + match (params, strings) with + | [], [result] -> ([], result) + | (p : Typedtree.function_param) :: params, ty :: strings -> + let typed, result = split params strings in + ((Js_ts_annot.key_of p.fp_param, ty) :: typed, result) + | _ -> assert false + in + split params strings) + overloads); + deepest + | exception Unsubstitutable -> types + in + let rec bind params optionals types = + match (params, optionals, types) with + | [], [], [result] -> + Hashtbl.replace st.results (Js_ts_annot.key_of id) result + | ( (p : Typedtree.function_param) :: params, + optional :: optionals, + ty :: types ) -> + Hashtbl.replace st.params (Js_ts_annot.key_of p.fp_param) {ty; optional}; + bind params optionals types + | _ -> assert false + in + bind params optionals types + | _ -> () + +let is_type_declaration (item : Typedtree.structure_item) = + match item.str_desc with + | Tstr_type _ -> true + | _ -> false + +let header_of_structure ~module_name (str : Typedtree.structure) = + let config = + { + (config ()) with + option_payload_markers = + payload_markers ~env:str.str_final_env ~var:declaration_var; + } + in + let type_env = Type_env.root () in + let output_file_relative = module_name ^ ".res.ts" in + let resolver = + Module_resolver.create_lazy_resolver ~config + ~extensions:[".res"; ".shim.ts"] ~exclude_file:(fun _ -> false) + in + let translation = + {str with str_items = List.filter is_type_declaration str.str_items} + |> Translate_structure.translate_structure ~config ~output_file_relative + ~resolver ~type_env + |> Translation.combine + |> Translation.add_type_declarations_from_module_equations ~type_env + in + Emit_js.emit_translation_as_string ~config + ~file_name:(Module_name.from_string_unsafe module_name) + ~output_file_relative ~resolver + ~input_cmt_translate_type_declarations: + Gentype_main.input_cmt_translate_type_declarations translation + +let collect ~module_name (str : Typedtree.structure) = + let st = Js_ts_annot.current () in + Hashtbl.reset st.params; + Hashtbl.reset st.results; + Hashtbl.reset st.generics; + Hashtbl.reset st.overloads; + Hashtbl.reset st.names; + let type_env = Type_env.root () in + (* Functions of nested modules are printed at the top level too. *) + let rec items (str : Typedtree.structure) = + List.iter + (fun (item : Typedtree.structure_item) -> + match item.str_desc with + | Tstr_value (_, vbs) -> + List.iter + (fun (vb : Typedtree.value_binding) -> + match vb.vb_pat.pat_desc with + | Tpat_var (id, _) -> collect_function st type_env id vb.vb_expr + | _ -> ()) + vbs + | Tstr_module {mb_expr = {mod_desc = Tmod_structure s}} -> items s + | _ -> ()) + str.str_items + in + items str; + st.header <- header_of_structure ~module_name str diff --git a/compiler/driver/rescript_compiler_driver.ml b/compiler/driver/rescript_compiler_driver.ml index 6ac6197cc85..f19b268415d 100644 --- a/compiler/driver/rescript_compiler_driver.ml +++ b/compiler/driver/rescript_compiler_driver.ml @@ -403,6 +403,11 @@ let command_line_flags () : (string * Bsc_args.spec * string) array = ( "-e", string_call (fun s -> eval s ~suffix:Literals.suffix_res), "(experimental) set the string to be evaluated in ReScript syntax" ); + ( "-bs-emit-ts", + set (Js_config.current ()).emit_ts, + "*internal* (experimental) Emit TypeScript: annotate top-level \ + functions, emit the module's type declarations, and write each output \ + with its suffix's .js replaced by .ts" ); ( "-bs-cmi-only", set (Js_config.current ()).cmi_only, "*internal* Stop after generating cmi file" ); diff --git a/compiler/gentype/gentype_config.ml b/compiler/gentype/gentype_config.ml index adf5123a272..8d5bf6d88bd 100644 --- a/compiler/gentype/gentype_config.ml +++ b/compiler/gentype/gentype_config.ml @@ -10,6 +10,16 @@ type module_resolution = | Bundler (** should use TS input's extension (e.g. `.gen.tsx`) on import statements *) +(** The nested-option markers [Some(v)] can be, for the values [v] of an + option's payload type: [Some(v)] is the frozen marker + [{BS_PRIVATE_NESTED_SOME_NONE: 0}] when [v] is [undefined], the marker of + depth [d + 1] when [v] is the marker of depth [d], and [v] itself + otherwise (Primitive_option.some). *) +type option_markers = + | No_markers (** [Some(v)] is [v] for every value of the payload type *) + | Depths of int list (** a marker of one of these depths, or [v] *) + | Any_depth (** a marker of a depth not known here, or [v] *) + type t = { bs_dependencies: string list; dep_paths: (string, string) Hashtbl.t; @@ -27,6 +37,9 @@ type t = { shims_map: Module_name.t Module_name_map.t; sources: string list; suffix: string; + option_payload_markers: Types.type_expr -> option_markers; + (** The markers [option] can hold for this payload [t], which the + option then prints beside [t] *) } let default = @@ -45,6 +58,7 @@ let default = shims_map = Module_name_map.empty; sources = []; suffix = ".bs.js"; + option_payload_markers = (fun _ -> No_markers); } (* ----- CLI-flag backing state ----------------------------------------- *) @@ -192,4 +206,5 @@ let build_config ~namespace = shims_map; sources = !(source_dirs_flag ()); suffix; + option_payload_markers = default.option_payload_markers; } diff --git a/compiler/gentype/translate_core_type.ml b/compiler/gentype/translate_core_type.ml index 6a961d32d5f..7f5ea0c21bf 100644 --- a/compiler/gentype/translate_core_type.ml +++ b/compiler/gentype/translate_core_type.ml @@ -1,19 +1,6 @@ open Gentype_common open! Translate_type_expr_from_types -let remove_option ~(label : Asttypes.arg_label) - (core_type : Typedtree.core_type) = - match (core_type.ctyp_desc, label) with - | Ttyp_constr (Path.Pident id, _, [t]), Optional {txt = lbl} - when Ident.name id = "option" -> - Some (lbl, t) - | ( Ttyp_constr (Pdot (Path.Pident name_space, id, _), _, [t]), - Optional {txt = lbl} ) - when (* This has a different representation in 4.03+ *) - Ident.name name_space = "FB" && id = "option" -> - Some (lbl, t) - | _ -> None - type process_variant = { no_payloads: (string * Typedtree.attributes) list; payloads: (string * Typedtree.attributes * Typedtree.core_type) list; @@ -62,30 +49,31 @@ let rec translate_arrow_type ~config ~type_vars_gen in ( List.rev_append dependencies rev_arg_deps, (Nolabel, type_) :: rev_args ) - | (Labelled {txt = lbl_txt} | Optional {txt = lbl_txt}) as label -> ( + | Labelled {txt = lbl_txt} -> let as_label = match attrs |> Annotation.get_gentype_as_renaming with | Some s -> s | None -> "" in - match typ |> remove_option ~label with - | None -> - let {dependencies; type_ = type1} = - typ |> translateCoreType_ ~config ~type_vars_gen ~type_env - in - ( List.rev_append dependencies rev_arg_deps, - ( Label - (match as_label = "" with - | true -> lbl_txt - | false -> as_label), - type1 ) - :: rev_args ) - | Some (lbl_txt, t1) -> - let {dependencies; type_ = type1} = - t1 |> translateCoreType_ ~config ~type_vars_gen ~type_env - in - ( List.rev_append dependencies rev_arg_deps, - (OptLabel lbl_txt, type1) :: rev_args ))) + let {dependencies; type_ = type1} = + typ |> translateCoreType_ ~config ~type_vars_gen ~type_env + in + ( List.rev_append dependencies rev_arg_deps, + ( Label + (match as_label = "" with + | true -> lbl_txt + | false -> as_label), + type1 ) + :: rev_args ) + | Optional {txt = lbl_txt} -> + (* The core type of an optional argument is its option's payload: + Typetexp wraps it in [option] *) + let {dependencies; type_ = type1} = + typ |> translateCoreType_ ~config ~type_vars_gen ~type_env + in + let type1 = some_type ~config typ.ctyp_type type1 in + ( List.rev_append dependencies rev_arg_deps, + (OptLabel lbl_txt, type1) :: rev_args )) ([], []) params in let {dependencies; type_ = ret_type} = @@ -137,6 +125,14 @@ and translateCoreType_ ~config ~type_vars_gen | true -> Closed | false -> Open) fields_translations + | Ttyp_constr (path, _, [payload]) when Path.same path Predef.path_option -> + let translation = + payload |> translateCoreType_ ~config ~type_vars_gen ~type_env + in + { + translation with + type_ = Option (some_type ~config payload.ctyp_type translation.type_); + } | Ttyp_constr (path, _, type_params) -> let params_translation = type_params |> translateCoreTypes_ ~config ~type_vars_gen ~type_env diff --git a/compiler/gentype/translate_type_expr_from_types.ml b/compiler/gentype/translate_type_expr_from_types.ml index da876f9c23b..a305d0aa25b 100644 --- a/compiler/gentype/translate_type_expr_from_types.ml +++ b/compiler/gentype/translate_type_expr_from_types.ml @@ -465,6 +465,46 @@ let process_variant row_fields = in row_fields |> loop ~no_payloads:[] ~payloads:[] ~unknowns:[] +(* The runtime's representation of [Some(v)] when [v] is [undefined] or + itself a marker: a frozen object holding the nesting depth + (Primitive_option.marker), at the type [depth]. *) +let nested_option_marker depth = + Object + ( Closed, + [ + { + mutable_ = Immutable; + name_js = "BS_PRIVATE_NESTED_SOME_NONE"; + optional = Mandatory; + type_ = depth; + doc_string = Doc_string.empty; + }; + ] ) + +(* The payload of an option as the option's representation holds it: the + payload's type, joined with the marker of each depth [Some(v)] can be, a + literal type, or [number] where the depth is not known. *) +let some_type ~config (payload : Types.type_expr) type_ = + let joined markers = + Variant + { + inherits = type_ :: markers; + no_payloads = []; + payloads = []; + polymorphic = false; + tag = None; + unboxed = false; + } + in + match config.Config.option_payload_markers payload with + | Config.No_markers | Config.Depths [] -> type_ + | Config.Depths depths -> + joined + (List.map + (fun d -> nested_option_marker (ident (string_of_int d))) + depths) + | Config.Any_depth -> joined [nested_option_marker number_t] + let rec translate_arrow_type ~config ~type_vars_gen ~type_env (params : Types.arg list) (ret : Types.type_expr) = let rev_arg_deps, rev_args = @@ -490,6 +530,7 @@ let rec translate_arrow_type ~config ~type_vars_gen ~type_env let {dependencies; type_ = type1} = t1 |> translateTypeExprFromTypes_ ~config ~type_vars_gen ~type_env in + let type1 = some_type ~config t1 type1 in ( List.rev_append dependencies rev_arg_deps, (OptLabel lbl_txt, type1) :: rev_args ))) ([], []) params @@ -534,6 +575,14 @@ and translateTypeExprFromTypes_ ~config ~type_vars_gen ~type_env | Tconstr (path, [{desc = Tlink te}], r) -> {type_expr with desc = Types.Tconstr (path, [te], r)} |> translateTypeExprFromTypes_ ~config ~type_vars_gen ~type_env + | Tconstr (path, [payload], _) when Path.same path Predef.path_option -> + let translation = + payload |> translateTypeExprFromTypes_ ~config ~type_vars_gen ~type_env + in + { + translation with + type_ = Option (some_type ~config payload translation.type_); + } | Tconstr (path, type_params, _) -> let params_translation = type_params diff --git a/compiler/typing/js_config.ml b/compiler/typing/js_config.ml index 616ea4d9034..1757c6e21ce 100644 --- a/compiler/typing/js_config.ml +++ b/compiler/typing/js_config.ml @@ -53,6 +53,7 @@ type t = { no_stdlib: bool ref; no_export: bool ref; as_pp: bool ref; + emit_ts: bool ref; self_stack: string Stack.t; } @@ -82,6 +83,7 @@ let create () = no_stdlib = ref false; no_export = ref false; as_pp = ref false; + emit_ts = ref false; self_stack = Stack.create (); } diff --git a/compiler/typing/js_config.mli b/compiler/typing/js_config.mli index 1185045a9f9..ee013d824b2 100644 --- a/compiler/typing/js_config.mli +++ b/compiler/typing/js_config.mli @@ -54,6 +54,9 @@ type t = { no_stdlib: bool ref; no_export: bool ref; as_pp: bool ref; + emit_ts: bool ref; + (** Print TypeScript: annotate top-level functions from the typed tree + and emit the module's type declarations. *) self_stack: string Stack.t; } From dcba023387d53c46e78b2dc74ee0f0197377364a Mon Sep 17 00:00:00 2001 From: Cristiano Calcagno Date: Tue, 24 Nov 2026 04:23:14 +0100 Subject: [PATCH 2/6] Add -bs-emit-ts build test with checked-in TypeScript and tsc output Add `tests/build_tests/emit_ts`, compiling ten example modules (`Arith`, `Arr`, `Gen`, `Memo`, `Nest`, `NestMatch`, `Opt`, `OptArg`, `Rec`, `Shape`) with `-bs-emit-ts` and recording `tsc --strict` diagnostics in `tsc.txt` against audited runtime declarations in `runtime-dts/` (`Primitive_option`, `Stdlib_Option`, `Stdlib_Array`). `tsc.txt` is empty, and all ten generated modules (46 units) verify end-to-end under TScert's `single-pass` branch. Signed-off-by: Cristiano Calcagno --- tests/build_tests/emit_ts/input.js | 30 +++++++ tests/build_tests/emit_ts/rescript.json | 10 +++ .../runtime-dts/Primitive_option.d.mts | 32 +++++++ .../emit_ts/runtime-dts/Stdlib_Array.d.mts | 10 +++ .../emit_ts/runtime-dts/Stdlib_Option.d.mts | 26 ++++++ tests/build_tests/emit_ts/src/Arith.res | 3 + tests/build_tests/emit_ts/src/Arith.res.ts | 16 ++++ tests/build_tests/emit_ts/src/Arr.res | 12 +++ tests/build_tests/emit_ts/src/Arr.res.ts | 26 ++++++ tests/build_tests/emit_ts/src/Gen.res | 17 ++++ tests/build_tests/emit_ts/src/Gen.res.ts | 46 ++++++++++ tests/build_tests/emit_ts/src/Memo.res | 6 ++ tests/build_tests/emit_ts/src/Memo.res.ts | 13 +++ tests/build_tests/emit_ts/src/Nest.res | 40 +++++++++ tests/build_tests/emit_ts/src/Nest.res.ts | 87 +++++++++++++++++++ tests/build_tests/emit_ts/src/NestMatch.res | 22 +++++ .../build_tests/emit_ts/src/NestMatch.res.ts | 43 +++++++++ tests/build_tests/emit_ts/src/Opt.res | 18 ++++ tests/build_tests/emit_ts/src/Opt.res.ts | 31 +++++++ tests/build_tests/emit_ts/src/OptArg.res | 27 ++++++ tests/build_tests/emit_ts/src/OptArg.res.ts | 55 ++++++++++++ tests/build_tests/emit_ts/src/Rec.res | 5 ++ tests/build_tests/emit_ts/src/Rec.res.ts | 30 +++++++ tests/build_tests/emit_ts/src/Shape.res | 18 ++++ tests/build_tests/emit_ts/src/Shape.res.ts | 30 +++++++ tests/build_tests/emit_ts/tsc.txt | 0 tests/build_tests/emit_ts/tsconfig.json | 15 ++++ 27 files changed, 668 insertions(+) create mode 100644 tests/build_tests/emit_ts/input.js create mode 100644 tests/build_tests/emit_ts/rescript.json create mode 100644 tests/build_tests/emit_ts/runtime-dts/Primitive_option.d.mts create mode 100644 tests/build_tests/emit_ts/runtime-dts/Stdlib_Array.d.mts create mode 100644 tests/build_tests/emit_ts/runtime-dts/Stdlib_Option.d.mts create mode 100644 tests/build_tests/emit_ts/src/Arith.res create mode 100644 tests/build_tests/emit_ts/src/Arith.res.ts create mode 100644 tests/build_tests/emit_ts/src/Arr.res create mode 100644 tests/build_tests/emit_ts/src/Arr.res.ts create mode 100644 tests/build_tests/emit_ts/src/Gen.res create mode 100644 tests/build_tests/emit_ts/src/Gen.res.ts create mode 100644 tests/build_tests/emit_ts/src/Memo.res create mode 100644 tests/build_tests/emit_ts/src/Memo.res.ts create mode 100644 tests/build_tests/emit_ts/src/Nest.res create mode 100644 tests/build_tests/emit_ts/src/Nest.res.ts create mode 100644 tests/build_tests/emit_ts/src/NestMatch.res create mode 100644 tests/build_tests/emit_ts/src/NestMatch.res.ts create mode 100644 tests/build_tests/emit_ts/src/Opt.res create mode 100644 tests/build_tests/emit_ts/src/Opt.res.ts create mode 100644 tests/build_tests/emit_ts/src/OptArg.res create mode 100644 tests/build_tests/emit_ts/src/OptArg.res.ts create mode 100644 tests/build_tests/emit_ts/src/Rec.res create mode 100644 tests/build_tests/emit_ts/src/Rec.res.ts create mode 100644 tests/build_tests/emit_ts/src/Shape.res create mode 100644 tests/build_tests/emit_ts/src/Shape.res.ts create mode 100644 tests/build_tests/emit_ts/tsc.txt create mode 100644 tests/build_tests/emit_ts/tsconfig.json diff --git a/tests/build_tests/emit_ts/input.js b/tests/build_tests/emit_ts/input.js new file mode 100644 index 00000000000..6859bd0d86f --- /dev/null +++ b/tests/build_tests/emit_ts/input.js @@ -0,0 +1,30 @@ +// @ts-check + +// The examples compiled with -bs-emit-ts. The generated src/*.res.ts are +// checked in, and so is tsc.txt: what tsc --strict reports for them against +// the runtime declarations in runtime-dts/. + +import * as assert from "node:assert"; +import * as child_process from "node:child_process"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import { setup } from "#dev/process"; + +const { execBuildOrThrow, execClean } = setup(import.meta.dirname); + +await execClean(); +await execBuildOrThrow(); + +const tsc = child_process.spawnSync( + process.execPath, + [ + path.join(import.meta.dirname, "../../../node_modules/typescript/bin/tsc"), + "-p", + ".", + "--pretty", + "false", + ], + { cwd: import.meta.dirname, encoding: "utf8" }, +); +assert.equal(tsc.stderr, ""); +await fs.writeFile(path.join(import.meta.dirname, "tsc.txt"), tsc.stdout); diff --git a/tests/build_tests/emit_ts/rescript.json b/tests/build_tests/emit_ts/rescript.json new file mode 100644 index 00000000000..b94e83093d1 --- /dev/null +++ b/tests/build_tests/emit_ts/rescript.json @@ -0,0 +1,10 @@ +{ + "name": "emit_ts", + "sources": ["src"], + "package-specs": { + "module": "esmodule", + "in-source": true + }, + "suffix": ".res.js", + "compiler-flags": ["-bs-emit-ts"] +} diff --git a/tests/build_tests/emit_ts/runtime-dts/Primitive_option.d.mts b/tests/build_tests/emit_ts/runtime-dts/Primitive_option.d.mts new file mode 100644 index 00000000000..b3738139e98 --- /dev/null +++ b/tests/build_tests/emit_ts/runtime-dts/Primitive_option.d.mts @@ -0,0 +1,32 @@ +// External contract for Primitive_option.some and valFromOption +// (packages/@rescript/runtime/Primitive_option.res), the boxing of a payload +// into Some and its unboxing, one signature per nesting of the payload: a +// primitive A, an option of one, and an option of an option of one. +// - some(x) is the frozen marker {BS_PRIVATE_NESTED_SOME_NONE: 0} when x is +// undefined, the marker of depth d + 1 when x is not null and its key +// BS_PRIVATE_NESTED_SOME_NONE reads a defined d, and x otherwise. +// - valFromOption(x) is undefined when x is not null and its key reads 0, the +// marker of depth d - 1 when it reads another defined d, and x otherwise. +// A string, number, boolean or bigint is not undefined and owns no such key, +// and its standard prototype chain, untampered, holds none, so x is returned; +// a value at a marker type reads its depth at the key. +type M0 = { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }; +type M1 = { readonly BS_PRIVATE_NESTED_SOME_NONE: 1 }; +export declare function some( + x: A, +): A; +export declare function some( + x: undefined | A, +): A | M0; +export declare function some( + x: undefined | A | M0, +): A | M0 | M1; +export declare function valFromOption< + A extends string | number | boolean | bigint, +>(x: A): A; +export declare function valFromOption< + A extends string | number | boolean | bigint, +>(x: A | M0): undefined | A; +export declare function valFromOption< + A extends string | number | boolean | bigint, +>(x: A | M0 | M1): undefined | A | M0; diff --git a/tests/build_tests/emit_ts/runtime-dts/Stdlib_Array.d.mts b/tests/build_tests/emit_ts/runtime-dts/Stdlib_Array.d.mts new file mode 100644 index 00000000000..e34feeac12e --- /dev/null +++ b/tests/build_tests/emit_ts/runtime-dts/Stdlib_Array.d.mts @@ -0,0 +1,10 @@ +// External contract for the one function of Stdlib_Array the examples use +// (packages/@rescript/runtime/Stdlib_Array.res): reduce(arr, init, f) is +// arr.reduce(f, init), the standard Array.prototype.reduce, untampered. It +// calls f with the accumulator, an element, its index and the array, for +// each index present, and returns init for an empty array. +export declare function reduce( + arr: readonly A[], + init: B, + f: (acc: B, x: A, index: number, array: readonly A[]) => B, +): B; diff --git a/tests/build_tests/emit_ts/runtime-dts/Stdlib_Option.d.mts b/tests/build_tests/emit_ts/runtime-dts/Stdlib_Option.d.mts new file mode 100644 index 00000000000..9166b9e6848 --- /dev/null +++ b/tests/build_tests/emit_ts/runtime-dts/Stdlib_Option.d.mts @@ -0,0 +1,26 @@ +// External contract for the two functions of Stdlib_Option +// (packages/@rescript/runtime/Stdlib_Option.res) the examples use, in terms +// of Primitive_option.some and valFromOption (Primitive_option.d.mts): +// - map(opt, f) is undefined for undefined, else some(f(valFromOption(opt))), +// calling f once with one argument; stated at primitive payloads, where +// some and valFromOption return their argument; +// - getOr(opt, d) is d for undefined, else valFromOption(opt); stated at a +// primitive A, an option of one, and an option of an option of one. +type M0 = { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }; +type M1 = { readonly BS_PRIVATE_NESTED_SOME_NONE: 1 }; +export declare function map< + A extends string | number | boolean | bigint, + B extends string | number | boolean | bigint, +>(opt: undefined | A, f: (x: A) => B): undefined | B; +export declare function getOr( + opt: undefined | A, + d: A, +): A; +export declare function getOr( + opt: undefined | A | M0, + d: undefined | A, +): undefined | A; +export declare function getOr( + opt: undefined | A | M0 | M1, + d: undefined | A | M0, +): undefined | A | M0; diff --git a/tests/build_tests/emit_ts/src/Arith.res b/tests/build_tests/emit_ts/src/Arith.res new file mode 100644 index 00000000000..c04d1199476 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Arith.res @@ -0,0 +1,3 @@ +let add = (a: int, b: int) => a + b +let scale = (x: float, k: float) => x *. k +. 1.0 +let mean = (a: int, b: int) => Int.toFloat(a + b) /. 2.0 diff --git a/tests/build_tests/emit_ts/src/Arith.res.ts b/tests/build_tests/emit_ts/src/Arith.res.ts new file mode 100644 index 00000000000..af127a62e21 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Arith.res.ts @@ -0,0 +1,16 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +export function add(a: number, b: number): number { + return a + b | 0; +} + +export function scale(x: number, k: number): number { + return x * k + 1.0; +} + +export function mean(a: number, b: number): number { + return (a + b | 0) / 2.0; +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/Arr.res b/tests/build_tests/emit_ts/src/Arr.res new file mode 100644 index 00000000000..849ae495d46 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Arr.res @@ -0,0 +1,12 @@ +let rec sumFrom = (xs: array, i: int) => + if i >= Array.length(xs) { + 0 + } else { + xs[i]->Option.getOr(0) + sumFrom(xs, i + 1) + } + +let squares = (xs: array) => Array.map(xs, x => x * x) + +let total = (xs: array) => Array.reduce(xs, 0, (acc, x) => acc + x) + +let sumOfSquares = (xs: array) => sumFrom(squares(xs), 0) diff --git a/tests/build_tests/emit_ts/src/Arr.res.ts b/tests/build_tests/emit_ts/src/Arr.res.ts new file mode 100644 index 00000000000..4cbb862716e --- /dev/null +++ b/tests/build_tests/emit_ts/src/Arr.res.ts @@ -0,0 +1,26 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Stdlib_Array from "@rescript/runtime/lib/es6/Stdlib_Array.mjs"; +import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; + +export function sumFrom(xs: number[], i: number): number { + if (i >= xs.length) { + return 0; + } else { + return Stdlib_Option.getOr(xs[i], 0) + sumFrom(xs, i + 1 | 0) | 0; + } +} + +export function squares(xs: number[]): number[] { + return xs.map(x => x * x | 0); +} + +export function total(xs: number[]): number { + return Stdlib_Array.reduce(xs, 0, (acc, x) => acc + x | 0); +} + +export function sumOfSquares(xs: number[]): number { + return sumFrom(squares(xs), 0); +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/Gen.res b/tests/build_tests/emit_ts/src/Gen.res new file mode 100644 index 00000000000..e1ef078670c --- /dev/null +++ b/tests/build_tests/emit_ts/src/Gen.res @@ -0,0 +1,17 @@ +let id = x => x + +let konst = (x, _y) => x + +let second = (_x: 'a, y: 'b): 'b => y + +let pair = (a, b) => (a, b) + +let applyTwice = (f, x) => f(f(x)) + +let getOr = (o, d) => + switch o { + | Some(v) => v + | None => d + } + +let useId = (n: int) => id(n) + applyTwice(x => x + 1, n) diff --git a/tests/build_tests/emit_ts/src/Gen.res.ts b/tests/build_tests/emit_ts/src/Gen.res.ts new file mode 100644 index 00000000000..950d4532f6e --- /dev/null +++ b/tests/build_tests/emit_ts/src/Gen.res.ts @@ -0,0 +1,46 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; + +export function id(x: T1): T1 { + return x; +} + +export function konst(x: T1, _y: T2): T1 { + return x; +} + +export function second(_x: a, y: b): b { + return y; +} + +export function pair(a: T1, b: T2): [T1, T2] { + return [ + a, + b + ]; +} + +export function applyTwice(f: (_1:T1) => T1, x: T1): T1 { + return f(f(x)); +} + +export function getOr(o: (undefined | T1), d: T1): T1; +export function getOr(o: (undefined | ( + (undefined | T1) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | T1)): (undefined | T1); +export function getOr(o: (undefined | ( + (undefined | T1) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | T1)): (undefined | T1) { + if (o !== undefined) { + return Primitive_option.valFromOption(o); + } else { + return d; + } +} + +export function useId(n: number): number { + return n + ((n + 1 | 0) + 1 | 0) | 0; +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/Memo.res b/tests/build_tests/emit_ts/src/Memo.res new file mode 100644 index 00000000000..0c0d0698ba1 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Memo.res @@ -0,0 +1,6 @@ +// A cache of a lookup that may find nothing: the cached value is option, +// so a cache read is option>. +let find = (xs: array, k: int) => xs->Array.find(x => x == k) + +let cached = (cache: dict>, xs, k) => + cache->Dict.get(Int.toString(k))->Option.getOr(find(xs, k)) diff --git a/tests/build_tests/emit_ts/src/Memo.res.ts b/tests/build_tests/emit_ts/src/Memo.res.ts new file mode 100644 index 00000000000..65d90e527e6 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Memo.res.ts @@ -0,0 +1,13 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; + +export function find(xs: number[], k: number): (undefined | number) { + return xs.find(x => x === k); +} + +export function cached(cache: {[id: string]: (undefined | number)}, xs: number[], k: number): (undefined | number) { + return Stdlib_Option.getOr(cache[k.toString()], find(xs, k)); +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/Nest.res b/tests/build_tests/emit_ts/src/Nest.res new file mode 100644 index 00000000000..7071225a856 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Nest.res @@ -0,0 +1,40 @@ +type box<'a> = {v: option<'a>} + +type opt<'a> = option<'a> + +type nested = option> + +type callback = (~x: option=?) => int + +let keep = (o: option>) => o + +let keepAlias = (o: opt<'a>) => o + +let keepNested = (o: nested) => o + +let skip = (o: option) => + switch o { + | Some(_) => 1 + | None => 0 + } + +let rewrap = (o: option<'a>) => + switch o { + | Some(x) => Some(x) + | None => None + } + +let boxed = (x: int) => {v: Some(x)} + +let call = (f: callback) => f() + +// A record owning the marker key at run time: Some(Some(r)) is the marker of +// depth r.depth + 1, so its options print a marker of any depth. No +// declaration of Primitive_option.some states such a payload, so wrapping +// one fails tsc. +type keyed = { + @as("BS_PRIVATE_NESTED_SOME_NONE") depth: int, + tag: string, +} + +let keepKeyed = (x: option>) => x diff --git a/tests/build_tests/emit_ts/src/Nest.res.ts b/tests/build_tests/emit_ts/src/Nest.res.ts new file mode 100644 index 00000000000..9fb75865395 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Nest.res.ts @@ -0,0 +1,87 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; + +export type box = { readonly v: (undefined | ( + a + | { readonly BS_PRIVATE_NESTED_SOME_NONE: number })) }; + +export type opt = (undefined | ( + a + | { readonly BS_PRIVATE_NESTED_SOME_NONE: number })); + +export type nested = (undefined | ( + (undefined | number) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })); + +export type callback = (x:(undefined | ( + (undefined | number) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }))) => number; + +export type keyed = { readonly BS_PRIVATE_NESTED_SOME_NONE: number; readonly tag: string }; + +export function keep(o: (undefined | ( + (undefined | number) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }))): (undefined | ( + (undefined | number) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })) { + return o; +} + +export function keepAlias(o: opt): opt { + return o; +} + +export function keepNested(o: nested): nested { + return o; +} + +export function skip(o: (undefined | ( + void + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }))): number { + if (o !== undefined) { + return 1; + } else { + return 0; + } +} + +export function rewrap(o: (undefined | a)): (undefined | a); +export function rewrap(o: (undefined | ( + (undefined | a) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }))): (undefined | ( + (undefined | a) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })); +export function rewrap(o: (undefined | ( + (undefined | a) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }))): (undefined | ( + (undefined | a) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })) { + if (o !== undefined) { + return Primitive_option.some(Primitive_option.valFromOption(o)); + } +} + +export function boxed(x: number): box { + return { + v: x + }; +} + +export function call(f: callback): number { + return f(undefined); +} + +export function keepKeyed(x: (undefined | ( + (undefined | ( + keyed + | { readonly BS_PRIVATE_NESTED_SOME_NONE: number })) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: number }))): (undefined | ( + (undefined | ( + keyed + | { readonly BS_PRIVATE_NESTED_SOME_NONE: number })) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: number })) { + return x; +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/NestMatch.res b/tests/build_tests/emit_ts/src/NestMatch.res new file mode 100644 index 00000000000..3a07461a988 --- /dev/null +++ b/tests/build_tests/emit_ts/src/NestMatch.res @@ -0,0 +1,22 @@ +// Nested options unwrapped, which the primitive bound on Primitive_option +// refuses. + +let getOr = (o: option<'a>, d: 'a) => + switch o { + | Some(v) => v + | None => d + } + +// The generic getOr at 'a = option. +let useNested = (o: option>) => getOr(o, Some(3)) + +// The same call on constants, which the optimizer folds to None. +let useNestedFolded = () => getOr(Some(None), Some(3)) + +// A nested match. +let inner = (o: option>) => + switch o { + | Some(Some(n)) => n + | Some(None) => -1 + | None => 0 + } diff --git a/tests/build_tests/emit_ts/src/NestMatch.res.ts b/tests/build_tests/emit_ts/src/NestMatch.res.ts new file mode 100644 index 00000000000..dcbec6624ca --- /dev/null +++ b/tests/build_tests/emit_ts/src/NestMatch.res.ts @@ -0,0 +1,43 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Primitive_option from "@rescript/runtime/lib/es6/Primitive_option.mjs"; + +export function getOr(o: (undefined | a), d: a): a; +export function getOr(o: (undefined | ( + (undefined | a) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a); +export function getOr(o: (undefined | ( + (undefined | a) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 })), d: (undefined | a)): (undefined | a) { + if (o !== undefined) { + return Primitive_option.valFromOption(o); + } else { + return d; + } +} + +export function useNested(o: (undefined | ( + (undefined | number) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }))): (undefined | number) { + return getOr(o, 3); +} + +export function useNestedFolded(): (undefined | number) { + return; +} + +export function inner(o: (undefined | ( + (undefined | number) + | { readonly BS_PRIVATE_NESTED_SOME_NONE: 0 }))): number { + if (o === undefined) { + return 0; + } + let n = Primitive_option.valFromOption(o); + if (n !== undefined) { + return n; + } else { + return -1; + } +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/Opt.res b/tests/build_tests/emit_ts/src/Opt.res new file mode 100644 index 00000000000..6e53bb4212a --- /dev/null +++ b/tests/build_tests/emit_ts/src/Opt.res @@ -0,0 +1,18 @@ +let orZero = (o: option) => + switch o { + | Some(n) => n + | None => 0 + } + +let double = (o: option) => Option.map(o, n => n * 2) + +let firstPositive = (a: int, b: int) => + if a > 0 { + Some(a) + } else if b > 0 { + Some(b) + } else { + None + } + +let none = (): option => None diff --git a/tests/build_tests/emit_ts/src/Opt.res.ts b/tests/build_tests/emit_ts/src/Opt.res.ts new file mode 100644 index 00000000000..69d4b5528ef --- /dev/null +++ b/tests/build_tests/emit_ts/src/Opt.res.ts @@ -0,0 +1,31 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Stdlib_Option from "@rescript/runtime/lib/es6/Stdlib_Option.mjs"; + +export function orZero(o: (undefined | number)): number { + if (o !== undefined) { + return o; + } else { + return 0; + } +} + +export function double(o: (undefined | number)): (undefined | number) { + return Stdlib_Option.map(o, n => (n << 1)); +} + +export function firstPositive(a: number, b: number): (undefined | number) { + if (a > 0) { + return a; + } else if (b > 0) { + return b; + } else { + return; + } +} + +export function none(): (undefined | number) { + return; +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/OptArg.res b/tests/build_tests/emit_ts/src/OptArg.res new file mode 100644 index 00000000000..56abb79200c --- /dev/null +++ b/tests/build_tests/emit_ts/src/OptArg.res @@ -0,0 +1,27 @@ +let scale = (x: int, ~by=2) => x * by + +let greet = (~name, ~greeting=?) => + switch greeting { + | Some(g) => g ++ " " ++ name + | None => "Hello " ++ name + } + +let offset = (~from=0, x: int) => x - from + +let clamp = (~lo=0, ~hi=100, x: int) => + if x < lo { + lo + } else if x > hi { + hi + } else { + x + } + +let wrap = (x, ~tag=?) => + switch tag { + | Some(t) => (t, x) + | None => ("none", x) + } + +let useAll = () => + scale(3) + scale(3, ~by=4) + offset(5) + clamp(500) + String.length(greet(~name="a")) diff --git a/tests/build_tests/emit_ts/src/OptArg.res.ts b/tests/build_tests/emit_ts/src/OptArg.res.ts new file mode 100644 index 00000000000..3d42627bfd6 --- /dev/null +++ b/tests/build_tests/emit_ts/src/OptArg.res.ts @@ -0,0 +1,55 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +export function scale(x: number, byOpt?: number): number { + let by = byOpt !== undefined ? byOpt : 2; + return x * by | 0; +} + +export function greet(name: string, greeting?: string): string { + if (greeting !== undefined) { + return greeting + " " + name; + } else { + return "Hello " + name; + } +} + +export function offset(fromOpt: (undefined | number), x: number): number { + let from = fromOpt !== undefined ? fromOpt : 0; + return x - from | 0; +} + +export function clamp(loOpt: (undefined | number), hiOpt: (undefined | number), x: number): number { + let lo = loOpt !== undefined ? loOpt : 0; + let hi = hiOpt !== undefined ? hiOpt : 100; + if (x < lo) { + return lo; + } else if (x > hi) { + return hi; + } else { + return x; + } +} + +export function wrap(x: T1, tag?: string): [string, T1] { + if (tag !== undefined) { + return [ + tag, + x + ]; + } else { + return [ + "none", + x + ]; + } +} + +export function useAll(): number { + let by = 2; + let by$1 = 4; + let from = 0; + return ((((3 * by | 0) + (3 * by$1 | 0) | 0) + (5 - from | 0) | 0) + clamp(undefined, undefined, 500) | 0) + greet("a", undefined).length | 0; +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/Rec.res b/tests/build_tests/emit_ts/src/Rec.res new file mode 100644 index 00000000000..31f9846c52c --- /dev/null +++ b/tests/build_tests/emit_ts/src/Rec.res @@ -0,0 +1,5 @@ +type point = {x: int, y: int, label: string} + +let make = (x: int, y: int) => {x, y, label: "p"} +let norm1 = (p: point) => Math.Int.abs(p.x) + Math.Int.abs(p.y) +let moveX = (p: point, dx: int) => {...p, x: p.x + dx} diff --git a/tests/build_tests/emit_ts/src/Rec.res.ts b/tests/build_tests/emit_ts/src/Rec.res.ts new file mode 100644 index 00000000000..18fea30c25d --- /dev/null +++ b/tests/build_tests/emit_ts/src/Rec.res.ts @@ -0,0 +1,30 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +export type point = { + readonly x: number; + readonly y: number; + readonly label: string +}; + +export function make(x: number, y: number): point { + return { + x: x, + y: y, + label: "p" + }; +} + +export function norm1(p: point): number { + return Math.abs(p.x) + Math.abs(p.y) | 0; +} + +export function moveX(p: point, dx: number): point { + return { + x: p.x + dx | 0, + y: p.y, + label: p.label + }; +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/Shape.res b/tests/build_tests/emit_ts/src/Shape.res new file mode 100644 index 00000000000..256b532f9f2 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Shape.res @@ -0,0 +1,18 @@ +type shape = + | Circle(float) + | Rect(float, float) + | Empty + +let area = (s: shape) => + switch s { + | Circle(r) => r *. r *. 3.14 + | Rect(w, h) => w *. h + | Empty => 0.0 + } + +let describe = (s: shape) => + switch s { + | Circle(_) => "circle" + | Rect(_, _) => "rect" + | Empty => "empty" + } diff --git a/tests/build_tests/emit_ts/src/Shape.res.ts b/tests/build_tests/emit_ts/src/Shape.res.ts new file mode 100644 index 00000000000..6fa8c82c0c3 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Shape.res.ts @@ -0,0 +1,30 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +export type shape = + "Empty" + | { TAG: "Circle"; _0: number } + | { TAG: "Rect"; _0: number; _1: number }; + +export function area(s: shape): number { + if (typeof s !== "object") { + return 0.0; + } + if (s.TAG !== "Circle") { + return s._0 * s._1; + } + let r = s._0; + return r * r * 3.14; +} + +export function describe(s: shape): string { + if (typeof s !== "object") { + return "empty"; + } else if (s.TAG === "Circle") { + return "circle"; + } else { + return "rect"; + } +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/tsc.txt b/tests/build_tests/emit_ts/tsc.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/tests/build_tests/emit_ts/tsconfig.json b/tests/build_tests/emit_ts/tsconfig.json new file mode 100644 index 00000000000..17fd0ff0874 --- /dev/null +++ b/tests/build_tests/emit_ts/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "module": "ESNext", + "moduleResolution": "Bundler", + "target": "ES2022", + "noEmit": true, + "allowImportingTsExtensions": true, + "skipLibCheck": false, + "paths": { + "@rescript/runtime/lib/es6/*.mjs": ["./runtime-dts/*.d.mts"] + } + }, + "include": ["src/*.res.ts"] +} From caf62886c7e85f23d4e585e626253626ae87dbc6 Mon Sep 17 00:00:00 2001 From: Cristiano Calcagno Date: Tue, 24 Nov 2026 05:16:40 +0100 Subject: [PATCH 3/6] Emit cross-module imports, const exports, tail-call params and local types under -bs-emit-ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Why: Multi-module programs, non-function exports, tail-recursive functions and local refs or deferred initializations need five extensions under `-bs-emit-ts` so both `tsc --strict` and TScert accept the emitted TypeScript: - Same-package ML module imports use the emitted TypeScript suffix (`.res.ts`, `.mts`, `.cts`), and `Js_ts_collect` resolves cross-module type dependencies with `Bundler` resolution and that suffix so function signatures, value bindings and type declarations import types from `./Mod.res.ts`. - Top-level non-function bindings collect their monomorphic types from the typed tree, propagate annotations across `Lam_coercion`'s `Ident.rename`, and print immutable bindings as `export const x: T = …` rather than live `export let` bindings. - Inline export checks compare the printed name from `Ext_pp_scope` against `Ext_ident.convert id.name` (excluding `default`), so reserved names such as `eval` print `export function $$eval` while scope-collision renames stay in `export { … }`. - Tail-call lowering (`Lam_compile`) propagates parameter annotations and overload origins when introducing `_param`. - `Js_stmt_make.define_variable` retains `= undefined` under `-bs-emit-ts`, `Js_ts_collect` records monomorphic local binding types and record/tuple field types, `Lam_pass_sroa` propagates field types to scalar-replaced locals (such as `ref(None)`), and `Js_dump` annotates uninitialized or `undefined`-initialized locals. JS modified (-bs-emit-ts cross-module imports and const/reserved exports): Example: // Expr.res: type expr = Lit(int) | ... let zero = Lit(0) // Eval.res: let eval = (e: Expr.expr) => Expr.simplify(e) Before (js): // Expr.res.ts let zero = { TAG: "Lit", _0: 0 }; export { zero, } // Eval.res.ts import * as Expr from "./Expr.res.js"; function $$eval(e: Expr_expr): Expr_expr { return Expr.simplify(e); } export { $$eval, } After (js): // Expr.res.ts export const zero: expr = { TAG: "Lit", _0: 0 }; // Eval.res.ts import * as Expr from "./Expr.res.ts"; import type {expr as Expr_expr} from './Expr.res.ts'; export function $$eval(e: Expr_expr): Expr_expr { return Expr.simplify(e); } JS modified (-bs-emit-ts tail-call parameter and uninitialized local types): Example: let rec unwrapNeg = (e: expr): expr => switch e { | Neg(Neg(inner)) => unwrapNeg(inner) | _ => e } let find = (xs: array) => { let found = ref(None) … found.contents } Before (js): export function unwrapNeg(_e): expr { while (true) { … } } export function find(xs: number[]): (undefined | number) { let found; … return found; } After (js): export function unwrapNeg(_e: expr): expr { while (true) { … } } export function find(xs: number[]): (undefined | number) { let found: (undefined | number) = undefined; … return found; } Review: Does JavaScript or genType output change outside -bs-emit-ts? No: all emission and annotation hooks are gated on `Js_ts_annot.enabled ()`. Signed-off-by: Cristiano Calcagno --- compiler/backend/js_dump.ml | 49 ++++++- compiler/backend/js_dump_lit.ml | 2 + compiler/backend/js_stmt_make.ml | 2 +- compiler/backend/js_ts_annot.ml | 73 +++++++++- compiler/backend/lam_coercion.ml | 2 + compiler/backend/lam_compile.ml | 1 + compiler/backend/lam_pass_sroa.ml | 1 + .../platform/native/js_name_of_module_id.ml | 20 ++- compiler/driver/js_ts_collect.ml | 132 ++++++++++++++++-- 9 files changed, 253 insertions(+), 29 deletions(-) diff --git a/compiler/backend/js_dump.ml b/compiler/backend/js_dump.ml index b4dd3795a5a..49c82111459 100644 --- a/compiler/backend/js_dump.ml +++ b/compiler/backend/js_dump.ml @@ -263,6 +263,13 @@ let pp_var_declare cxt f id = P.string f L.let_; P.space f; let acxt = Ext_pp_scope.ident cxt f id in + (if Js_ts_annot.enabled () then + match Js_ts_annot.local_type id with + | Some ty -> + P.string f ":"; + P.space f; + P.string f ty + | None -> ()); semi f; acxt @@ -528,7 +535,8 @@ let rec pp_function ~return_unit ~async ~is_method ?directive cxt (f : P.t) param_body (); semi f | Name_top x -> - let export = Js_ts_annot.export_inline x in + let printed, _ = Ext_pp_scope.str_of_ident inner_cxt x in + let export = Js_ts_annot.export_inline x ~printed in (* [-bs-emit-ts]: the function's overloads, each a declaration without a body before the function, which carries its own signature. An overload takes no [async]. *) @@ -1248,7 +1256,7 @@ and variable_declaration top cxt f (variable : J.variable_declaration) : cxt = match variable with | {ident = i; value = None; ident_info; _} -> if ident_info.used_stats = Dead_pure then cxt else pp_var_declare cxt f i - | {ident = name; value = Some e; ident_info = {used_stats; _}} -> ( + | {ident = name; value = Some e; property; ident_info = {used_stats; _}} -> ( match used_stats with | Dead_pure -> cxt | Dead_non_pure -> @@ -1273,7 +1281,42 @@ and variable_declaration top cxt f (variable : J.variable_declaration) : cxt = semi f; cxt | _ -> - let cxt = pp_var_assign cxt f name in + let cxt = + if top && Js_ts_annot.enabled () then ( + let is_const = property <> Variable in + let printed, _ = Ext_pp_scope.str_of_ident cxt name in + if is_const && Js_ts_annot.export_inline name ~printed then ( + P.string f L.export; + P.space f); + P.string f (if is_const then L.const_ else L.let_); + P.space f; + let cxt = Ext_pp_scope.ident cxt f name in + (match Js_ts_annot.value_type name with + | Some ty -> + P.string f ":"; + P.space f; + P.string f ty + | None -> ()); + P.space f; + P.string f L.eq; + P.space f; + cxt) + else if Js_ts_annot.enabled () then + match (e.expression_desc, Js_ts_annot.local_type name) with + | Undefined _, Some ty -> + P.string f L.let_; + P.space f; + let cxt = Ext_pp_scope.ident cxt f name in + P.string f ":"; + P.space f; + P.string f ty; + P.space f; + P.string f L.eq; + P.space f; + cxt + | _ -> pp_var_assign cxt f name + else pp_var_assign cxt f name + in let cxt = expression ~level:1 cxt f e in semi f; cxt)) diff --git a/compiler/backend/js_dump_lit.ml b/compiler/backend/js_dump_lit.ml index ee04aa63d98..6ce26f5ca33 100644 --- a/compiler/backend/js_dump_lit.ml +++ b/compiler/backend/js_dump_lit.ml @@ -35,6 +35,8 @@ let arrow = "=>" let let_ = "let" +let const_ = "const" + let return = "return" (* let eq = "=" *) diff --git a/compiler/backend/js_stmt_make.ml b/compiler/backend/js_stmt_make.ml index 52d00f39cf2..1661965c2a5 100644 --- a/compiler/backend/js_stmt_make.ml +++ b/compiler/backend/js_stmt_make.ml @@ -64,7 +64,7 @@ let declare_variable ~kind (ident : Ident.t) : t = let define_variable ~kind (v : Ident.t) (exp : J.expression) : t = match exp.expression_desc with - | Undefined _ -> declare_variable ~kind v + | Undefined _ when not (Js_ts_annot.enabled ()) -> declare_variable ~kind v | _ -> let property : J.property = kind in let ident_info : J.ident_info = {used_stats = NA} in diff --git a/compiler/backend/js_ts_annot.ml b/compiler/backend/js_ts_annot.ml index 4147766b206..4488f4be8e9 100644 --- a/compiler/backend/js_ts_annot.ml +++ b/compiler/backend/js_ts_annot.ml @@ -20,26 +20,40 @@ type param = { type state = { params: (key, param) Hashtbl.t; (** parameter ident -> its annotation *) results: (key, string) Hashtbl.t; (** top-level function -> result type *) + values: (key, string) Hashtbl.t; + (** top-level non-function binding -> its type *) + locals: (key, string) Hashtbl.t; + (** local binding -> its type, emitted when initialized to [undefined] + or declared without an initializer *) + sroa_fields: (key, string array) Hashtbl.t; + (** local record/tuple binding -> its field types by index, propagated + to the scalar variables when [Lam_pass_sroa] replaces the block *) generics: (key, string list) Hashtbl.t; (** top-level function -> its type parameters, in order of occurrence, each with its bound if it has one *) overloads: (key, ((key * string) list * string) list) Hashtbl.t; (** top-level function -> its overloads, each its parameters' types by their idents and its result type *) + param_origin: (key, key) Hashtbl.t; + (** renamed parameter ident -> original typedtree parameter ident *) names: (string, int) Hashtbl.t; (** top-level function name -> its stamp, to report lost stamps *) mutable header: string; (** the module's type declarations *) mutable exports: Ident.t list; (** the program's exports *) inline_exports: (key, unit) Hashtbl.t; - (** exports printed as [export function] *) + (** exports printed as [export function] or [export const] *) } let fresh () = { params = Hashtbl.create 16; results = Hashtbl.create 16; + values = Hashtbl.create 16; + locals = Hashtbl.create 16; + sroa_fields = Hashtbl.create 16; generics = Hashtbl.create 16; overloads = Hashtbl.create 16; + param_origin = Hashtbl.create 16; names = Hashtbl.create 16; header = ""; exports = []; @@ -72,7 +86,14 @@ let overloads (id : Ident.t) = | Some overloads -> overloads | None -> [] -let overload_param_type typed (id : Ident.t) = List.assoc_opt (key_of id) typed +let overload_param_type typed (id : Ident.t) = + let k = key_of id in + match List.assoc_opt k typed with + | Some _ as res -> res + | None -> ( + match Hashtbl.find_opt (current ()).param_origin k with + | Some orig -> List.assoc_opt orig typed + | None -> None) (* Report, once per top-level function the printer names, whether its stamp and its parameters' stamps are the typed tree's. *) @@ -101,6 +122,10 @@ let param_type (id : Ident.t) = Hashtbl.find_opt (current ()).params (key_of id) let result_type (id : Ident.t) = Hashtbl.find_opt (current ()).results (key_of id) +let value_type (id : Ident.t) = Hashtbl.find_opt (current ()).values (key_of id) + +let local_type (id : Ident.t) = Hashtbl.find_opt (current ()).locals (key_of id) + let type_params (id : Ident.t) = match Hashtbl.find_opt (current ()).generics (key_of id) with | Some vars -> "<" ^ String.concat ", " vars ^ ">" @@ -111,15 +136,49 @@ let set_exports exports = st.exports <- exports; Hashtbl.reset st.inline_exports -(* A top-level function is printed [export function f] when it is exported - under its own name. The printer is assumed to print a top-level function - under its source name. *) -let export_inline (id : Ident.t) = +let rename ~(from : Ident.t) ~(to_ : Ident.t) = + if enabled () then ( + let st = current () in + let src = key_of from in + let dst = key_of to_ in + let copy tbl = + match Hashtbl.find_opt tbl src with + | Some v -> Hashtbl.replace tbl dst v + | None -> () + in + copy st.params; + copy st.results; + copy st.values; + copy st.locals; + copy st.sroa_fields; + copy st.generics; + copy st.overloads; + let orig = + match Hashtbl.find_opt st.param_origin src with + | Some orig -> orig + | None -> src + in + if Hashtbl.mem st.params src then Hashtbl.replace st.param_origin dst orig) + +let sroa_replace ~(block : Ident.t) ~(fields : Ident.t array) = + if enabled () then + let st = current () in + match Hashtbl.find_opt st.sroa_fields (key_of block) with + | Some field_tys when Array.length field_tys = Array.length fields -> + Array.iteri + (fun i id -> Hashtbl.replace st.locals (key_of id) field_tys.(i)) + fields + | _ -> () + +(* A top-level binding is printed [export function f] or [export const x] + when it is exported under its own printed name. *) +let export_inline (id : Ident.t) ~(printed : string) = enabled () && let st = current () in List.exists (fun e -> Ident.same e id) st.exports - && Ext_ident.convert id.name = id.name + && id.name <> "default" + && String.equal printed (Ext_ident.convert id.name) && (Hashtbl.replace st.inline_exports (key_of id) (); true) diff --git a/compiler/backend/lam_coercion.ml b/compiler/backend/lam_coercion.ml index 73c1becbbbf..90d5f65ab33 100644 --- a/compiler/backend/lam_coercion.ml +++ b/compiler/backend/lam_coercion.ml @@ -101,6 +101,7 @@ let handle_exports (meta : Lam_stats.t) (lambda_exports : Lambda.t list) } else let newid = Ident.rename original_export_id in + Js_ts_annot.rename ~from:original_export_id ~to_:newid; let kind : Lambda.let_kind = Alias in Lam_util.alias_ident_or_global meta newid id NA; { @@ -128,6 +129,7 @@ let handle_exports (meta : Lam_stats.t) (lambda_exports : Lambda.t list) of size 4 instead of 2 *) let newid = Ident.rename original_export_id in + Js_ts_annot.rename ~from:original_export_id ~to_:newid; (let arity = Lam_arity_analysis.get_arity meta lam in if not (Lam_arity.first_arity_na arity) then Hash_ident.add meta.ident_tbl newid diff --git a/compiler/backend/lam_compile.ml b/compiler/backend/lam_compile.ml index e49f06a5b9c..7b4031c7342 100644 --- a/compiler/backend/lam_compile.ml +++ b/compiler/backend/lam_compile.ml @@ -1797,6 +1797,7 @@ let compile output_prefix = | None -> ret.immutable_mask.(i) <- false; let v = Ext_ident.create ("_" ^ param.name) in + Js_ts_annot.rename ~from:param ~to_:v; (v, Map_ident.add param v new_params) | Some v -> (v, new_params) in diff --git a/compiler/backend/lam_pass_sroa.ml b/compiler/backend/lam_pass_sroa.ml index b5c97333b06..0906afb445b 100644 --- a/compiler/backend/lam_pass_sroa.ml +++ b/compiler/backend/lam_pass_sroa.ml @@ -110,6 +110,7 @@ let replace_block ~assignable ~block ~info ~initializers body = if not (analyze block uses body) then None else let fields = fields_for_block block info field_count in + Js_ts_annot.sroa_replace ~block ~fields; let body = rewrite block fields uses body in Array.iteri (fun index use -> diff --git a/compiler/backend/platform/native/js_name_of_module_id.ml b/compiler/backend/platform/native/js_name_of_module_id.ml index 5eec0113cf2..99099937f99 100644 --- a/compiler/backend/platform/native/js_name_of_module_id.ml +++ b/compiler/backend/platform/native/js_name_of_module_id.ml @@ -105,15 +105,18 @@ let string_of_module_id (dep_module_id : Lam_module_ident.t) in pkg.pkg_rel_path // js_file | Package_found ({suffix} as dep_pkg), Package_found cur_pkg -> - let js_file = - Ext_namespace.js_name_of_modulename dep_module_id.id.name case - suffix - in - if Js_packages_info.same_package_by_name current_package_info dep_package_info then + let suffix = + if Js_ts_annot.enabled () then Js_ts_annot.ts_suffix suffix + else suffix + in + let js_file = + Ext_namespace.js_name_of_modulename dep_module_id.id.name case + suffix + in Ext_path.node_rebase_file ~from:cur_pkg.rel_path ~to_:dep_pkg.rel_path js_file (* TODO: we assume that both [x] and [path] could only be relative path @@ -122,7 +125,12 @@ let string_of_module_id (dep_module_id : Lam_module_ident.t) else if Js_packages_info.is_runtime_package dep_package_info then get_runtime_module_path dep_module_id current_package_info module_system - else dep_pkg.pkg_rel_path // js_file + else + let js_file = + Ext_namespace.js_name_of_modulename dep_module_id.id.name case + suffix + in + dep_pkg.pkg_rel_path // js_file | Package_script, Package_script -> ( let js_file = Ext_namespace.js_name_of_modulename dep_module_id.id.name case diff --git a/compiler/driver/js_ts_collect.ml b/compiler/driver/js_ts_collect.ml index 979b706efd7..dd229e0169e 100644 --- a/compiler/driver/js_ts_collect.ml +++ b/compiler/driver/js_ts_collect.ml @@ -2,7 +2,25 @@ function annotations and module type declarations from the typed tree using genType's translation, storing them in [Js_ts_annot]. *) -let config () = {Gentype_config.default with everything = true} +let current_package_layout () = + let info = Js_packages_state.get_packages_info () in + match Js_packages_info.query_package_infos info Esmodule with + | Package_found {rel_path; suffix} -> (rel_path, Js_ts_annot.ts_suffix suffix) + | _ -> ( + match Js_packages_info.query_package_infos info Commonjs with + | Package_found {rel_path; suffix} -> + (rel_path, Js_ts_annot.ts_suffix suffix) + | _ -> ("", ".res.ts")) + +let config () = + let _, ts_suffix = current_package_layout () in + { + Gentype_config.default with + everything = true; + module_resolution = Bundler; + generated_file_extension = Some ts_suffix; + project_root = Ext_path.package_dir (); + } (* [option] holds [undefined] for [None], and for [Some(v)] the value [Primitive_option.some(v)]: the frozen marker @@ -156,6 +174,11 @@ let ts_of_signature ~env ~var type_env (type_exprs : Types.type_expr list) = acc (Type_vars.free t.type_)) [] translations in + let deps = + List.concat_map + (fun (t : Translate_type_expr_from_types.translation) -> t.dependencies) + translations + in ( List.map (fun (t : Translate_type_expr_from_types.translation) -> type_to_string t.type_) @@ -163,7 +186,8 @@ let ts_of_signature ~env ~var type_env (type_exprs : Types.type_expr list) = type_vars, List.map (fun (t : Translate_type_expr_from_types.translation) -> t.type_) - translations ) + translations, + deps ) let is_optional (p : Typedtree.function_param) = match p.fp_lbl with @@ -263,10 +287,65 @@ let rec depth_assignments n = the deepest instance's, whose parameters admit every overload's. An optional argument then prints [p: undefined | t], one form for every overload. *) -let collect_function (st : Js_ts_annot.state) type_env (id : Ident.t) +let record_or_tuple_fields ~env (t : Types.type_expr) = + match (Ctype.expand_head_opt env t).desc with + | Ttuple ts -> Some ts + | Tconstr (path, args, _) -> ( + match Env.find_type path env with + | {type_params; type_kind = Type_record (labels, _)} + when List.length type_params = List.length args -> ( + let pairs = List.combine (List.map Ctype.repr type_params) args in + match + List.map + (fun (ld : Types.label_declaration) -> substitute pairs ld.ld_type) + labels + with + | fields -> Some fields + | exception Unsubstitutable -> None) + | _ -> None + | exception Not_found -> None) + | _ -> None + +let collect_locals (st : Js_ts_annot.state) ~deps type_env + (e : Typedtree.expression) = + let iter = + { + Tast_iterator.default_iterator with + value_binding = + (fun self vb -> + (match vb.vb_pat.pat_desc with + | Tpat_var (id, _) -> ( + let env = vb.vb_expr.exp_env in + let ty = vb.vb_pat.pat_type in + let strings, type_vars, _, local_deps = + ts_of_signature ~env ~var:declaration_var type_env [ty] + in + if type_vars = [] then ( + deps := local_deps @ !deps; + match strings with + | [s] -> Hashtbl.replace st.locals (Js_ts_annot.key_of id) s + | _ -> ()); + match record_or_tuple_fields ~env ty with + | Some field_tys -> + let fstrings, fvars, _, fdeps = + ts_of_signature ~env ~var:declaration_var type_env field_tys + in + if fvars = [] then ( + deps := fdeps @ !deps; + Hashtbl.replace st.sroa_fields (Js_ts_annot.key_of id) + (Array.of_list fstrings)) + | None -> ()) + | _ -> ()); + Tast_iterator.default_iterator.value_binding self vb); + } + in + iter.expr iter e + +let collect_function (st : Js_ts_annot.state) ~deps type_env (id : Ident.t) (e : Typedtree.expression) = match e.exp_desc with | Texp_function {params; body} -> + collect_locals st ~deps type_env body; Hashtbl.replace st.names id.name id.stamp; let env = e.exp_env in (* The type variables an option's encoding reaches: each is bounded. *) @@ -286,7 +365,7 @@ let collect_function (st : Js_ts_annot.state) type_env (id : Ident.t) @ [body.exp_type] in let optionals, _ = trailing_optionals ~env ~var params in - let _ = ts_of_signature ~env ~var type_env (signature optionals) in + ignore (ts_of_signature ~env ~var type_env (signature optionals)); let payload = !reached in let optionals = if payload = [] then optionals else List.map (fun _ -> false) optionals @@ -303,9 +382,10 @@ let collect_function (st : Js_ts_annot.state) type_env (id : Ident.t) acc (Ctype.free_variables t)) [] base in - let strings, type_vars, translated = + let strings, type_vars, translated, sig_deps = ts_of_signature ~env ~var type_env (base @ vars) in + deps := sig_deps @ !deps; let arity = List.length base in let types = List.filteri (fun i _ -> i < arity) strings in let translated_signature = List.filteri (fun i _ -> i < arity) translated in @@ -343,7 +423,7 @@ let collect_function (st : Js_ts_annot.state) type_env (id : Ident.t) | None -> (v, fresh)) named in - let strings, _, _ = + let strings, _, _, _ = ts_of_signature ~env ~var type_env (List.map (substitute pairs) base) in strings @@ -384,14 +464,23 @@ let collect_function (st : Js_ts_annot.state) type_env (id : Ident.t) | _ -> assert false in bind params optionals types - | _ -> () + | _ -> + let strings, type_vars, _, val_deps = + ts_of_signature ~env:e.exp_env ~var:declaration_var type_env [e.exp_type] + in + if type_vars = [] then ( + deps := val_deps @ !deps; + match strings with + | [ty] -> Hashtbl.replace st.values (Js_ts_annot.key_of id) ty + | _ -> ()) let is_type_declaration (item : Typedtree.structure_item) = match item.str_desc with | Tstr_type _ -> true | _ -> false -let header_of_structure ~module_name (str : Typedtree.structure) = +let header_of_structure ~module_name ~deps (str : Typedtree.structure) = + let rel_path, ts_suffix = current_package_layout () in let config = { (config ()) with @@ -400,7 +489,10 @@ let header_of_structure ~module_name (str : Typedtree.structure) = } in let type_env = Type_env.root () in - let output_file_relative = module_name ^ ".res.ts" in + let output_file_relative = + if rel_path = "" then module_name ^ ts_suffix + else Filename.concat rel_path (module_name ^ ts_suffix) + in let resolver = Module_resolver.create_lazy_resolver ~config ~extensions:[".res"; ".shim.ts"] ~exclude_file:(fun _ -> false) @@ -412,6 +504,16 @@ let header_of_structure ~module_name (str : Typedtree.structure) = |> Translation.combine |> Translation.add_type_declarations_from_module_equations ~type_env in + let extra_import_types = + Translation.translate_dependencies ~config ~output_file_relative ~resolver + deps + in + let translation = + { + translation with + import_types = translation.import_types @ extra_import_types; + } + in Emit_js.emit_translation_as_string ~config ~file_name:(Module_name.from_string_unsafe module_name) ~output_file_relative ~resolver @@ -422,11 +524,16 @@ let collect ~module_name (str : Typedtree.structure) = let st = Js_ts_annot.current () in Hashtbl.reset st.params; Hashtbl.reset st.results; + Hashtbl.reset st.values; + Hashtbl.reset st.locals; + Hashtbl.reset st.sroa_fields; Hashtbl.reset st.generics; Hashtbl.reset st.overloads; + Hashtbl.reset st.param_origin; Hashtbl.reset st.names; let type_env = Type_env.root () in - (* Functions of nested modules are printed at the top level too. *) + let deps = ref [] in + (* Functions and values of nested modules are printed at the top level too. *) let rec items (str : Typedtree.structure) = List.iter (fun (item : Typedtree.structure_item) -> @@ -435,7 +542,8 @@ let collect ~module_name (str : Typedtree.structure) = List.iter (fun (vb : Typedtree.value_binding) -> match vb.vb_pat.pat_desc with - | Tpat_var (id, _) -> collect_function st type_env id vb.vb_expr + | Tpat_var (id, _) -> + collect_function st ~deps type_env id vb.vb_expr | _ -> ()) vbs | Tstr_module {mb_expr = {mod_desc = Tmod_structure s}} -> items s @@ -443,4 +551,4 @@ let collect ~module_name (str : Typedtree.structure) = str.str_items in items str; - st.header <- header_of_structure ~module_name str + st.header <- header_of_structure ~module_name ~deps:!deps str From b722717bbd7ba14e7cc8523b9c37cbc3a982e6de Mon Sep 17 00:00:00 2001 From: Cristiano Calcagno Date: Tue, 24 Nov 2026 05:17:08 +0100 Subject: [PATCH 4/6] Add multi-module Expr and Eval examples to -bs-emit-ts build test Add a two-module AST and evaluator (`Expr` and `Eval`) to `tests/build_tests/emit_ts` along with an audited `Primitive_int.d.mts` contract for `Primitive_int.div`, exercising cross-module `.res` imports of types and values, recursive variants, tail recursion, non-function `const` exports, `result`, `@unboxed` and polymorphic variants, `ref` with `while`/`for` loops, array writes, and mutable record fields. `tsc.txt` remains empty (0 diagnostics), and all 12 generated modules (59/59 units) verify under TScert `single-pass` (`0406f7e50`). Signed-off-by: Cristiano Calcagno --- .../emit_ts/runtime-dts/Primitive_int.d.mts | 4 + tests/build_tests/emit_ts/src/Eval.res | 128 +++++++++++ tests/build_tests/emit_ts/src/Eval.res.ts | 205 ++++++++++++++++++ tests/build_tests/emit_ts/src/Expr.res | 55 +++++ tests/build_tests/emit_ts/src/Expr.res.ts | 180 +++++++++++++++ 5 files changed, 572 insertions(+) create mode 100644 tests/build_tests/emit_ts/runtime-dts/Primitive_int.d.mts create mode 100644 tests/build_tests/emit_ts/src/Eval.res create mode 100644 tests/build_tests/emit_ts/src/Eval.res.ts create mode 100644 tests/build_tests/emit_ts/src/Expr.res create mode 100644 tests/build_tests/emit_ts/src/Expr.res.ts diff --git a/tests/build_tests/emit_ts/runtime-dts/Primitive_int.d.mts b/tests/build_tests/emit_ts/runtime-dts/Primitive_int.d.mts new file mode 100644 index 00000000000..7eeae7faa8b --- /dev/null +++ b/tests/build_tests/emit_ts/runtime-dts/Primitive_int.d.mts @@ -0,0 +1,4 @@ +// External contract for Primitive_int.div +// (packages/@rescript/runtime/Primitive_int.res): throws Division_by_zero +// when y === 0, otherwise returns (x / y) | 0, a number. +export declare function div(x: number, y: number): number; diff --git a/tests/build_tests/emit_ts/src/Eval.res b/tests/build_tests/emit_ts/src/Eval.res new file mode 100644 index 00000000000..a0f956f4999 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Eval.res @@ -0,0 +1,128 @@ +type binding = { + name: string, + value: int, +} + +type evalError = + | DivByZero + | UnboundVar(string) + +type stats = { + mutable okCount: int, + mutable errCount: int, + mutable sum: int, +} + +type program = { + exprs: array, + fallback: int, +} + +type status = [#ok | #divByZero | #unbound] + +@unboxed +type valueOrNote = + | Int(int) + | Note(string) + +let lookup = (env: array, target: string): option => { + let found = ref(None) + let i = ref(0) + while i.contents < Array.length(env) && found.contents == None { + switch env[i.contents] { + | Some(b) if b.name == target => found := Some(b.value) + | _ => () + } + i := i.contents + 1 + } + found.contents +} + +let rec eval = (env: array, e: Expr.expr): result => + switch e { + | Lit(n) => Ok(n) + | Var(name) => + switch lookup(env, name) { + | Some(v) => Ok(v) + | None => Error(UnboundVar(name)) + } + | Neg(a) => + switch eval(env, a) { + | Ok(v) => Ok(-v) + | Error(err) => Error(err) + } + | Bin(op, a, b) => + switch (eval(env, a), eval(env, b)) { + | (Error(err), _) | (_, Error(err)) => Error(err) + | (Ok(x), Ok(y)) => + switch op { + | Add => Ok(x + y) + | Sub => Ok(x - y) + | Mul => Ok(x * y) + | Div => + if y == 0 { + Error(DivByZero) + } else { + Ok(x / y) + } + } + } + } + +let evalSimplified = (env: array, e: Expr.expr): result => + eval(env, Expr.simplify(e)) + +let summarize = (res: result): valueOrNote => + switch res { + | Ok(v) => Int(v) + | Error(DivByZero) => Note("div-by-zero") + | Error(UnboundVar(name)) => Note("unbound:" ++ name) + } + +let classify = (res: result): status => + switch res { + | Ok(_) => #ok + | Error(DivByZero) => #divByZero + | Error(UnboundVar(_)) => #unbound + } + +let evalProgram = (env: array, prog: program): array => { + let out: array = [] + for i in 0 to Array.length(prog.exprs) - 1 { + switch prog.exprs[i] { + | Some(e) => + let v = switch evalSimplified(env, e) { + | Ok(n) => n + | Error(_) => prog.fallback + } + Array.push(out, v) + | None => () + } + } + out +} + +let negateInPlace = (xs: array): unit => + for i in 0 to Array.length(xs) - 1 { + switch xs[i] { + | Some(v) => xs[i] = -v + | None => () + } + } + +let runBatch = (env: array, exprs: array): stats => { + let st = {okCount: 0, errCount: 0, sum: 0} + for i in 0 to Array.length(exprs) - 1 { + switch exprs[i] { + | Some(e) => + switch evalSimplified(env, e) { + | Ok(v) => + st.okCount = st.okCount + 1 + st.sum = st.sum + v + | Error(_) => st.errCount = st.errCount + 1 + } + | None => () + } + } + st +} diff --git a/tests/build_tests/emit_ts/src/Eval.res.ts b/tests/build_tests/emit_ts/src/Eval.res.ts new file mode 100644 index 00000000000..2bd4882166b --- /dev/null +++ b/tests/build_tests/emit_ts/src/Eval.res.ts @@ -0,0 +1,205 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Expr from "./Expr.res.ts"; +import * as Primitive_int from "@rescript/runtime/lib/es6/Primitive_int.mjs"; + +import type {expr as Expr_expr} from './Expr.res.ts'; + +export type binding = { readonly name: string; readonly value: number }; + +export type evalError = + "DivByZero" + | { TAG: "UnboundVar"; _0: string }; + +export type stats = { + okCount: number; + errCount: number; + sum: number +}; + +export type program = { readonly exprs: Expr_expr[]; readonly fallback: number }; + +export type status = "ok" | "divByZero" | "unbound"; + +export type valueOrNote = number | string; + +export function lookup(env: binding[], target: string): (undefined | number) { + let found: (undefined | number) = undefined; + let i = 0; + while (i < env.length && found === undefined) { + let b = env[i]; + if (b !== undefined && b.name === target) { + found = b.value; + } + i = i + 1 | 0; + }; + return found; +} + +export function $$eval(env: binding[], e: Expr_expr): + { TAG: "Ok"; _0: number } + | { TAG: "Error"; _0: evalError } { + switch (e.TAG) { + case "Lit" : + return { + TAG: "Ok", + _0: e._0 + }; + case "Var" : + let name = e._0; + let v = lookup(env, name); + if (v !== undefined) { + return { + TAG: "Ok", + _0: v + }; + } else { + return { + TAG: "Error", + _0: { + TAG: "UnboundVar", + _0: name + } + }; + } + case "Neg" : + let v$1 = $$eval(env, e._0); + if (v$1.TAG === "Ok") { + return { + TAG: "Ok", + _0: -v$1._0 | 0 + }; + } else { + return { + TAG: "Error", + _0: v$1._0 + }; + } + case "Bin" : + let match = $$eval(env, e._1); + let match$1 = $$eval(env, e._2); + if (match.TAG !== "Ok") { + return { + TAG: "Error", + _0: match._0 + }; + } + let x = match._0; + if (match$1.TAG !== "Ok") { + return { + TAG: "Error", + _0: match$1._0 + }; + } + let y = match$1._0; + switch (e._0) { + case "Add" : + return { + TAG: "Ok", + _0: x + y | 0 + }; + case "Sub" : + return { + TAG: "Ok", + _0: x - y | 0 + }; + case "Mul" : + return { + TAG: "Ok", + _0: x * y | 0 + }; + case "Div" : + if (y === 0) { + return { + TAG: "Error", + _0: "DivByZero" + }; + } else { + return { + TAG: "Ok", + _0: Primitive_int.div(x, y) + }; + } + } + } +} + +export function evalSimplified(env: binding[], e: Expr_expr): + { TAG: "Ok"; _0: number } + | { TAG: "Error"; _0: evalError } { + return $$eval(env, Expr.simplify(e)); +} + +export function summarize(res: + { TAG: "Ok"; _0: number } + | { TAG: "Error"; _0: evalError }): valueOrNote { + if (res.TAG === "Ok") { + return res._0; + } + let name = res._0; + if (typeof name !== "object") { + return "div-by-zero"; + } else { + return "unbound:" + name._0; + } +} + +export function classify(res: + { TAG: "Ok"; _0: number } + | { TAG: "Error"; _0: evalError }): status { + if (res.TAG === "Ok") { + return "ok"; + } + let tmp = res._0; + if (typeof tmp !== "object") { + return "divByZero"; + } else { + return "unbound"; + } +} + +export function evalProgram(env: binding[], prog: program): number[] { + let out = []; + for (let i = 0, i_finish = prog.exprs.length; i < i_finish; ++i) { + let e = prog.exprs[i]; + if (e !== undefined) { + let n = $$eval(env, Expr.simplify(e)); + let v: number; + v = n.TAG === "Ok" ? n._0 : prog.fallback; + out.push(v); + } + } + return out; +} + +export function negateInPlace(xs: number[]): void { + for (let i = 0, i_finish = xs.length; i < i_finish; ++i) { + let v = xs[i]; + if (v !== undefined) { + xs[i] = -v | 0; + } + } +} + +export function runBatch(env: binding[], exprs: Expr_expr[]): stats { + let st = { + okCount: 0, + errCount: 0, + sum: 0 + }; + for (let i = 0, i_finish = exprs.length; i < i_finish; ++i) { + let e = exprs[i]; + if (e !== undefined) { + let v = $$eval(env, Expr.simplify(e)); + if (v.TAG === "Ok") { + st.okCount = st.okCount + 1 | 0; + st.sum = st.sum + v._0 | 0; + } else { + st.errCount = st.errCount + 1 | 0; + } + } + } + return st; +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/Expr.res b/tests/build_tests/emit_ts/src/Expr.res new file mode 100644 index 00000000000..c186000861a --- /dev/null +++ b/tests/build_tests/emit_ts/src/Expr.res @@ -0,0 +1,55 @@ +type op = Add | Sub | Mul | Div + +type rec expr = + | Lit(int) + | Var(string) + | Neg(expr) + | Bin(op, expr, expr) + +let zero = Lit(0) + +let rec unwrapNeg = (e: expr): expr => + switch e { + | Neg(Neg(inner)) => unwrapNeg(inner) + | _ => e + } + +let rec size = (e: expr): int => + switch e { + | Lit(_) | Var(_) => 1 + | Neg(a) => 1 + size(a) + | Bin(_, a, b) => 1 + size(a) + size(b) + } + +let rec depth = (e: expr): int => + switch e { + | Lit(_) | Var(_) => 1 + | Neg(a) => 1 + depth(a) + | Bin(_, a, b) => + let da = depth(a) + let db = depth(b) + 1 + (da > db ? da : db) + } + +let rec simplify = (e: expr): expr => + switch e { + | Lit(_) | Var(_) => e + | Neg(a) => + switch simplify(a) { + | Lit(n) => Lit(-n) + | Neg(inner) => inner + | sa => Neg(sa) + } + | Bin(op, a, b) => + switch (op, simplify(a), simplify(b)) { + | (Add, Lit(x), Lit(y)) => Lit(x + y) + | (Sub, Lit(x), Lit(y)) => Lit(x - y) + | (Mul, Lit(x), Lit(y)) => Lit(x * y) + | (Add, Lit(0), sb) => sb + | (Add, sa, Lit(0)) => sa + | (Mul, Lit(1), sb) => sb + | (Mul, sa, Lit(1)) => sa + | (Mul, Lit(0), _) | (Mul, _, Lit(0)) => Lit(0) + | (_, sa, sb) => Bin(op, sa, sb) + } + } diff --git a/tests/build_tests/emit_ts/src/Expr.res.ts b/tests/build_tests/emit_ts/src/Expr.res.ts new file mode 100644 index 00000000000..3206e4e6228 --- /dev/null +++ b/tests/build_tests/emit_ts/src/Expr.res.ts @@ -0,0 +1,180 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +export type op = "Add" | "Sub" | "Mul" | "Div"; + +export type expr = + { TAG: "Lit"; _0: number } + | { TAG: "Var"; _0: string } + | { TAG: "Neg"; _0: expr } + | { TAG: "Bin"; _0: op; _1: expr; _2: expr }; + +export function unwrapNeg(_e: expr): expr { + while (true) { + let e = _e; + if (e.TAG !== "Neg") { + return e; + } + let inner = e._0; + if (inner.TAG !== "Neg") { + return e; + } + _e = inner._0; + continue; + }; +} + +export function size(e: expr): number { + switch (e.TAG) { + case "Lit" : + case "Var" : + return 1; + case "Neg" : + return 1 + size(e._0) | 0; + case "Bin" : + return (1 + size(e._1) | 0) + size(e._2) | 0; + } +} + +export function depth(e: expr): number { + switch (e.TAG) { + case "Lit" : + case "Var" : + return 1; + case "Neg" : + return 1 + depth(e._0) | 0; + case "Bin" : + let da = depth(e._1); + let db = depth(e._2); + return 1 + ( + da > db ? da : db + ) | 0; + } +} + +export function simplify(e: expr): expr { + switch (e.TAG) { + case "Lit" : + case "Var" : + return e; + case "Neg" : + let n = simplify(e._0); + switch (n.TAG) { + case "Lit" : + return { + TAG: "Lit", + _0: -n._0 | 0 + }; + case "Neg" : + return n._0; + case "Var" : + case "Bin" : + return { + TAG: "Neg", + _0: n + }; + } + case "Bin" : + let op = e._0; + let match = simplify(e._1); + let match$1 = simplify(e._2); + switch (op) { + case "Add" : + if (match.TAG === "Lit") { + let x = match._0; + if (match$1.TAG === "Lit") { + return { + TAG: "Lit", + _0: x + match$1._0 | 0 + }; + } + if (x === 0) { + return match$1; + } + } + if (match$1.TAG === "Lit" && match$1._0 === 0) { + return match; + } else { + return { + TAG: "Bin", + _0: op, + _1: match, + _2: match$1 + }; + } + break; + case "Sub" : + if (match.TAG === "Lit" && match$1.TAG === "Lit") { + return { + TAG: "Lit", + _0: match._0 - match$1._0 | 0 + }; + } else { + return { + TAG: "Bin", + _0: op, + _1: match, + _2: match$1 + }; + } + case "Mul" : + let exit = 0; + if (match.TAG === "Lit") { + let x$1 = match._0; + if (match$1.TAG === "Lit") { + return { + TAG: "Lit", + _0: x$1 * match$1._0 | 0 + }; + } + if (x$1 === 1) { + return match$1; + } + exit = 2; + } else { + exit = 2; + } + if (exit === 2 && match$1.TAG === "Lit") { + let match$2 = match$1._0; + if (match$2 === 0) { + return { + TAG: "Lit", + _0: 0 + }; + } + if (match$2 === 1) { + return match; + } + } + if (match.TAG === "Lit" && match._0 === 0) { + return { + TAG: "Lit", + _0: 0 + }; + } else { + return { + TAG: "Bin", + _0: op, + _1: match, + _2: match$1 + }; + } + break; + case "Div" : + return { + TAG: "Bin", + _0: op, + _1: match, + _2: match$1 + }; + } + break; + } +} + +export const zero: expr = { + TAG: "Lit", + _0: 0 +}; + +/* No side effect */ From a9fd8b6ea1203121ed2b6944be57baf855124d64 Mon Sep 17 00:00:00 2001 From: Cristiano Calcagno Date: Tue, 24 Nov 2026 06:00:45 +0100 Subject: [PATCH 5/6] Annotate mutable local bindings under -bs-emit-ts Why: A mutable local binding (`property = Variable`, such as an SROA-unboxed `ref(All)` holding a string-union variant) widens in TypeScript when printed without a type annotation (`let filter = "All"` infers `string`, which fails when returned at `filter`). Annotating mutable locals with their collected monomorphic type keeps the narrowed union type intact. JS modified (-bs-emit-ts mutable local bindings): Example: let parseFilter = (flag: bool): TodoModel.filter => { let filter = ref(TodoModel.All) if flag { filter := TodoModel.Active } filter.contents } Before (js): export function parseFilter(flag: boolean): TodoModel_filter { let filter = "All"; if (flag) { filter = "Active"; } return filter; } After (js): export function parseFilter(flag: boolean): TodoModel_filter { let filter: TodoModel_filter = "All"; if (flag) { filter = "Active"; } return filter; } Review: Does JavaScript output change outside -bs-emit-ts? No: the annotation branch is gated on `Js_ts_annot.enabled ()`. Signed-off-by: Cristiano Calcagno --- compiler/backend/js_dump.ml | 6 ++++-- tests/build_tests/emit_ts/src/Eval.res.ts | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/compiler/backend/js_dump.ml b/compiler/backend/js_dump.ml index 49c82111459..5bbf03d160d 100644 --- a/compiler/backend/js_dump.ml +++ b/compiler/backend/js_dump.ml @@ -1302,8 +1302,10 @@ and variable_declaration top cxt f (variable : J.variable_declaration) : cxt = P.space f; cxt) else if Js_ts_annot.enabled () then - match (e.expression_desc, Js_ts_annot.local_type name) with - | Undefined _, Some ty -> + match + (property, e.expression_desc, Js_ts_annot.local_type name) + with + | Variable, _, Some ty | _, Undefined _, Some ty -> P.string f L.let_; P.space f; let cxt = Ext_pp_scope.ident cxt f name in diff --git a/tests/build_tests/emit_ts/src/Eval.res.ts b/tests/build_tests/emit_ts/src/Eval.res.ts index 2bd4882166b..5e4b085db08 100644 --- a/tests/build_tests/emit_ts/src/Eval.res.ts +++ b/tests/build_tests/emit_ts/src/Eval.res.ts @@ -25,7 +25,7 @@ export type valueOrNote = number | string; export function lookup(env: binding[], target: string): (undefined | number) { let found: (undefined | number) = undefined; - let i = 0; + let i: number = 0; while (i < env.length && found === undefined) { let b = env[i]; if (b !== undefined && b.name === target) { From d5158ff0ac33987b4d141c6ce06372b7b5807de8 Mon Sep 17 00:00:00 2001 From: Cristiano Calcagno Date: Tue, 24 Nov 2026 06:01:48 +0100 Subject: [PATCH 6/6] Add TScert-verified multi-module Todo web app to -bs-emit-ts build test Add a usable, styled Todo web app split across three ReScript modules (`TodoModel`, `TodoView`, `TodoApp`) plus a thin Node 26 HTTP adapter (`todo-server.mts`) to `tests/build_tests/emit_ts`. The verified ReScript core covers priorities, filters, search, inline editing, toggle-all, clear-completed, HTML escaping, URL/query parsing, variant-driven routing, and JSON responses, with zero `runtime-dts/` contracts. `tsc.txt` stays empty (0 diagnostics), all 15 modules (95/95 units; 36/36 for the Todo app) verify under TScert `single-pass` (`0406f7e50`), and all HTTP routes pass live against `todo-server.mts` on Node 26. Signed-off-by: Cristiano Calcagno --- tests/build_tests/emit_ts/src/TodoApp.res | 272 ++++++++++ tests/build_tests/emit_ts/src/TodoApp.res.ts | 467 ++++++++++++++++++ tests/build_tests/emit_ts/src/TodoModel.res | 171 +++++++ .../build_tests/emit_ts/src/TodoModel.res.ts | 265 ++++++++++ tests/build_tests/emit_ts/src/TodoView.res | 413 ++++++++++++++++ tests/build_tests/emit_ts/src/TodoView.res.ts | 360 ++++++++++++++ tests/build_tests/emit_ts/todo-server.mts | 34 ++ 7 files changed, 1982 insertions(+) create mode 100644 tests/build_tests/emit_ts/src/TodoApp.res create mode 100644 tests/build_tests/emit_ts/src/TodoApp.res.ts create mode 100644 tests/build_tests/emit_ts/src/TodoModel.res create mode 100644 tests/build_tests/emit_ts/src/TodoModel.res.ts create mode 100644 tests/build_tests/emit_ts/src/TodoView.res create mode 100644 tests/build_tests/emit_ts/src/TodoView.res.ts create mode 100644 tests/build_tests/emit_ts/todo-server.mts diff --git a/tests/build_tests/emit_ts/src/TodoApp.res b/tests/build_tests/emit_ts/src/TodoApp.res new file mode 100644 index 00000000000..3d9ac0fae97 --- /dev/null +++ b/tests/build_tests/emit_ts/src/TodoApp.res @@ -0,0 +1,272 @@ +type request = { + method: string, + path: string, + body: string, +} + +type response = { + status: int, + contentType: string, + body: string, +} + +type route = + | Home(TodoModel.filter, string) + | ListJson + | GetTodo(int) + | Create + | Toggle(int) + | Edit(int) + | CyclePriority(int) + | Delete(int) + | ToggleAll + | ClearCompleted + | BadId + | NotFound + +let todosPath = "/todos" +let todosPrefix = "/todos/" + +// Parse a non-negative decimal integer id. +let parseId = (text: string): option => { + let len = String.length(text) + if len == 0 { + None + } else { + let n = ref(0) + let valid = ref(true) + let i = ref(0) + while i.contents < len && valid.contents { + switch String.codePointAt(text, i.contents) { + | Some(c) if c >= 48 && c <= 57 => n := n.contents * 10 + (c - 48) + | _ => valid := false + } + i := i.contents + 1 + } + valid.contents ? Some(n.contents) : None + } +} + +let hexDigit = (code: option): option => + switch code { + | Some(c) if c >= 48 && c <= 57 => Some(c - 48) + | Some(c) if c >= 65 && c <= 70 => Some(c - 55) + | Some(c) if c >= 97 && c <= 102 => Some(c - 87) + | _ => None + } + +let decodeQueryValue = (raw: string): string => { + let len = String.length(raw) + let out = ref("") + let i = ref(0) + while i.contents < len { + let ch = String.charAt(raw, i.contents) + if ch == "+" { + out := out.contents ++ " " + i := i.contents + 1 + } else if ch == "%" && i.contents + 2 < len { + let h1 = hexDigit(String.codePointAt(raw, i.contents + 1)) + let h2 = hexDigit(String.codePointAt(raw, i.contents + 2)) + switch (h1, h2) { + | (Some(a), Some(b)) => + out := out.contents ++ String.fromCharCode(a * 16 + b) + i := i.contents + 3 + | _ => + out := out.contents ++ ch + i := i.contents + 1 + } + } else { + out := out.contents ++ ch + i := i.contents + 1 + } + } + out.contents +} + +let parseQuery = (qs: string): (TodoModel.filter, string) => { + let filter = ref(TodoModel.All) + let query = ref("") + if String.length(qs) > 0 { + let parts = String.split(qs, "&") + for i in 0 to Array.length(parts) - 1 { + switch parts[i] { + | Some(pair) => + let eq = String.indexOf(pair, "=") + if eq >= 0 { + let key = String.slice(pair, ~start=0, ~end=eq) + let value = decodeQueryValue(String.slice(pair, ~start=eq + 1)) + if key == "filter" { + filter := TodoModel.filterFromString(value) + } else if key == "q" { + query := value + } + } + | None => () + } + } + } + (filter.contents, query.contents) +} + +let parseCreateBody = (body: string): (string, TodoModel.priority) => { + let sep = String.indexOf(body, "|") + if sep >= 0 { + let prefix = String.slice(body, ~start=0, ~end=sep) + let rest = String.slice(body, ~start=sep + 1) + let p = String.toLowerCase(String.trim(prefix)) + if p == "low" || p == "medium" || p == "high" { + (rest, TodoModel.priorityFromString(p)) + } else { + (body, TodoModel.Medium) + } + } else { + (body, TodoModel.Medium) + } +} + +let parseRoute = (method: string, fullPath: string): route => { + let qIdx = String.indexOf(fullPath, "?") + let path = qIdx >= 0 ? String.slice(fullPath, ~start=0, ~end=qIdx) : fullPath + let qs = qIdx >= 0 ? String.slice(fullPath, ~start=qIdx + 1) : "" + if method == "GET" && path == "/" { + let (filter, query) = parseQuery(qs) + Home(filter, query) + } else if method == "GET" && path == todosPath { + ListJson + } else if method == "POST" && path == todosPath { + Create + } else if method == "POST" && path == "/todos/toggle-all" { + ToggleAll + } else if method == "POST" && path == "/todos/clear-completed" { + ClearCompleted + } else if String.startsWith(path, todosPrefix) { + let rest = String.slice(path, ~start=String.length(todosPrefix)) + if method == "POST" && String.endsWith(rest, "/toggle") { + let idText = String.slice(rest, ~start=0, ~end=String.length(rest) - 7) + switch parseId(idText) { + | Some(id) => Toggle(id) + | None => BadId + } + } else if method == "POST" && String.endsWith(rest, "/edit") { + let idText = String.slice(rest, ~start=0, ~end=String.length(rest) - 5) + switch parseId(idText) { + | Some(id) => Edit(id) + | None => BadId + } + } else if method == "POST" && String.endsWith(rest, "/priority") { + let idText = String.slice(rest, ~start=0, ~end=String.length(rest) - 9) + switch parseId(idText) { + | Some(id) => CyclePriority(id) + | None => BadId + } + } else if method == "DELETE" { + switch parseId(rest) { + | Some(id) => Delete(id) + | None => BadId + } + } else if method == "GET" { + switch parseId(rest) { + | Some(id) => GetTodo(id) + | None => BadId + } + } else { + NotFound + } + } else { + NotFound + } +} + +let escapeJsonString = (text: string): string => { + let out = ref("") + for i in 0 to String.length(text) - 1 { + let c = String.charAt(text, i) + let escaped = switch c { + | "\\" => "\\\\" + | "\"" => "\\\"" + | "\n" => "\\n" + | "\r" => "\\r" + | "\t" => "\\t" + | _ => c + } + out := out.contents ++ escaped + } + "\"" ++ out.contents ++ "\"" +} + +let todoJson = (t: TodoModel.todo): string => + "{\"id\":" ++ + Int.toString(t.id) ++ + ",\"title\":" ++ + escapeJsonString(t.title) ++ + ",\"done\":" ++ + (t.done ? "true" : "false") ++ + ",\"priority\":" ++ + escapeJsonString(TodoModel.priorityToString(t.priority)) ++ "}" + +let todosJson = (todos: array): string => + "[" ++ Array.join(Array.map(todos, todoJson), ",") ++ "]" + +let jsonResponse = (status: int, body: string): response => { + status, + contentType: "application/json; charset=utf-8", + body, +} + +let textResponse = (status: int, body: string): response => { + status, + contentType: "text/plain; charset=utf-8", + body, +} + +let handleRequest = (state: TodoModel.appState, req: request): (TodoModel.appState, response) => + switch parseRoute(req.method, req.path) { + | Home(filter, query) => ( + state, + { + status: 200, + contentType: "text/html; charset=utf-8", + body: TodoView.renderPage(state, filter, query), + }, + ) + | ListJson => (state, jsonResponse(200, todosJson(state.todos))) + | GetTodo(id) => + switch TodoModel.findTodo(state.todos, id) { + | Some(todo) => (state, jsonResponse(200, todoJson(todo))) + | None => (state, textResponse(404, "not found")) + } + | Create => + let (rawTitle, priority) = parseCreateBody(req.body) + let title = String.trim(rawTitle) + if String.length(title) == 0 { + (state, textResponse(400, "empty title")) + } else { + let next = TodoModel.addTodo(state, title, priority) + (next, jsonResponse(201, todosJson(next.todos))) + } + | Toggle(id) => + let next = TodoModel.toggleTodo(state, id) + (next, jsonResponse(200, todosJson(next.todos))) + | Edit(id) => + let title = String.trim(req.body) + if String.length(title) == 0 { + (state, textResponse(400, "empty title")) + } else { + let next = TodoModel.editTodo(state, id, title) + (next, jsonResponse(200, todosJson(next.todos))) + } + | CyclePriority(id) => + let next = TodoModel.cyclePriority(state, id) + (next, jsonResponse(200, todosJson(next.todos))) + | Delete(id) => + let next = TodoModel.deleteTodo(state, id) + (next, jsonResponse(200, todosJson(next.todos))) + | ToggleAll => + let next = TodoModel.toggleAll(state) + (next, jsonResponse(200, todosJson(next.todos))) + | ClearCompleted => + let next = TodoModel.clearCompleted(state) + (next, jsonResponse(200, todosJson(next.todos))) + | BadId => (state, textResponse(400, "bad id")) + | NotFound => (state, textResponse(404, "not found")) + } diff --git a/tests/build_tests/emit_ts/src/TodoApp.res.ts b/tests/build_tests/emit_ts/src/TodoApp.res.ts new file mode 100644 index 00000000000..69a2ad5fbdb --- /dev/null +++ b/tests/build_tests/emit_ts/src/TodoApp.res.ts @@ -0,0 +1,467 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as TodoView from "./TodoView.res.ts"; +import * as TodoModel from "./TodoModel.res.ts"; + +import type {appState as TodoModel_appState} from './TodoModel.res.ts'; + +import type {filter as TodoModel_filter} from './TodoModel.res.ts'; + +import type {priority as TodoModel_priority} from './TodoModel.res.ts'; + +import type {todo as TodoModel_todo} from './TodoModel.res.ts'; + +export type request = { + readonly method: string; + readonly path: string; + readonly body: string +}; + +export type response = { + readonly status: number; + readonly contentType: string; + readonly body: string +}; + +export type route = + "ListJson" + | "Create" + | "ToggleAll" + | "ClearCompleted" + | "BadId" + | "NotFound" + | { TAG: "Home"; _0: TodoModel_filter; _1: string } + | { TAG: "GetTodo"; _0: number } + | { TAG: "Toggle"; _0: number } + | { TAG: "Edit"; _0: number } + | { TAG: "CyclePriority"; _0: number } + | { TAG: "Delete"; _0: number }; + +export const todosPath: string = "/todos"; + +export const todosPrefix: string = "/todos/"; + +export function parseId(text: string): (undefined | number) { + let len = text.length; + if (len === 0) { + return; + } + let n: number = 0; + let valid: boolean = true; + let i: number = 0; + while (i < len && valid) { + let c = text.codePointAt(i); + if (c !== undefined && c >= 48 && c <= 57) { + n = (n * 10 | 0) + (c - 48 | 0) | 0; + } else { + valid = false; + } + i = i + 1 | 0; + }; + if (valid) { + return n; + } +} + +export function hexDigit(code: (undefined | number)): (undefined | number) { + if (code !== undefined) { + if (code >= 48 && code <= 57) { + return code - 48 | 0; + } else if (code >= 65 && code <= 70) { + return code - 55 | 0; + } else if (code >= 97 && code <= 102) { + return code - 87 | 0; + } else { + return; + } + } +} + +export function decodeQueryValue(raw: string): string { + let len = raw.length; + let out: string = ""; + let i: number = 0; + while (i < len) { + let ch = raw.charAt(i); + if (ch === "+") { + out = out + " "; + i = i + 1 | 0; + } else if (ch === "%" && (i + 2 | 0) < len) { + let h1 = hexDigit(raw.codePointAt(i + 1 | 0)); + let h2 = hexDigit(raw.codePointAt(i + 2 | 0)); + let exit = 0; + if (h1 !== undefined && h2 !== undefined) { + out = out + String.fromCharCode((h1 << 4) + h2 | 0); + i = i + 3 | 0; + } else { + exit = 1; + } + if (exit === 1) { + out = out + ch; + i = i + 1 | 0; + } + } else { + out = out + ch; + i = i + 1 | 0; + } + }; + return out; +} + +export function parseQuery(qs: string): [TodoModel_filter, string] { + let filter: TodoModel_filter = "All"; + let query: string = ""; + if (qs.length > 0) { + let parts = qs.split("&"); + for (let i = 0, i_finish = parts.length; i < i_finish; ++i) { + let pair = parts[i]; + if (pair !== undefined) { + let eq = pair.indexOf("="); + if (eq >= 0) { + let key = pair.slice(0, eq); + let value = decodeQueryValue(pair.slice(eq + 1 | 0)); + if (key === "filter") { + filter = TodoModel.filterFromString(value); + } else if (key === "q") { + query = value; + } + } + } + } + } + return [ + filter, + query + ]; +} + +export function parseCreateBody(body: string): [string, TodoModel_priority] { + let sep = body.indexOf("|"); + if (sep < 0) { + return [ + body, + "Medium" + ]; + } + let prefix = body.slice(0, sep); + let rest = body.slice(sep + 1 | 0); + let p = prefix.trim().toLowerCase(); + if (p === "low" || p === "medium" || p === "high") { + return [ + rest, + TodoModel.priorityFromString(p) + ]; + } else { + return [ + body, + "Medium" + ]; + } +} + +export function parseRoute(method: string, fullPath: string): route { + let qIdx = fullPath.indexOf("?"); + let path = qIdx >= 0 ? fullPath.slice(0, qIdx) : fullPath; + let qs = qIdx >= 0 ? fullPath.slice(qIdx + 1 | 0) : ""; + if (method === "GET" && path === "/") { + let match = parseQuery(qs); + return { + TAG: "Home", + _0: match[0], + _1: match[1] + }; + } + if (method === "GET" && path === todosPath) { + return "ListJson"; + } + if (method === "POST" && path === todosPath) { + return "Create"; + } + if (method === "POST" && path === "/todos/toggle-all") { + return "ToggleAll"; + } + if (method === "POST" && path === "/todos/clear-completed") { + return "ClearCompleted"; + } + if (!path.startsWith(todosPrefix)) { + return "NotFound"; + } + let rest = path.slice(todosPrefix.length); + if (method === "POST" && rest.endsWith("/toggle")) { + let idText = rest.slice(0, rest.length - 7 | 0); + let id = parseId(idText); + if (id !== undefined) { + return { + TAG: "Toggle", + _0: id + }; + } else { + return "BadId"; + } + } + if (method === "POST" && rest.endsWith("/edit")) { + let idText$1 = rest.slice(0, rest.length - 5 | 0); + let id$1 = parseId(idText$1); + if (id$1 !== undefined) { + return { + TAG: "Edit", + _0: id$1 + }; + } else { + return "BadId"; + } + } + if (method === "POST" && rest.endsWith("/priority")) { + let idText$2 = rest.slice(0, rest.length - 9 | 0); + let id$2 = parseId(idText$2); + if (id$2 !== undefined) { + return { + TAG: "CyclePriority", + _0: id$2 + }; + } else { + return "BadId"; + } + } + if (method === "DELETE") { + let id$3 = parseId(rest); + if (id$3 !== undefined) { + return { + TAG: "Delete", + _0: id$3 + }; + } else { + return "BadId"; + } + } + if (method !== "GET") { + return "NotFound"; + } + let id$4 = parseId(rest); + if (id$4 !== undefined) { + return { + TAG: "GetTodo", + _0: id$4 + }; + } else { + return "BadId"; + } +} + +export function escapeJsonString(text: string): string { + let out: string = ""; + for (let i = 0, i_finish = text.length; i < i_finish; ++i) { + let c = text.charAt(i); + let escaped: string; + switch (c) { + case "\t" : + escaped = "\\t"; + break; + case "\n" : + escaped = "\\n"; + break; + case "\r" : + escaped = "\\r"; + break; + case "\"" : + escaped = "\\\""; + break; + case "\\" : + escaped = "\\\\"; + break; + default: + escaped = c; + } + out = out + escaped; + } + return "\"" + out + "\""; +} + +export function todoJson(t: TodoModel_todo): string { + return "{\"id\":" + t.id.toString() + ",\"title\":" + escapeJsonString(t.title) + ",\"done\":" + ( + t.done ? "true" : "false" + ) + ",\"priority\":" + escapeJsonString(TodoModel.priorityToString(t.priority)) + "}"; +} + +export function todosJson(todos: TodoModel_todo[]): string { + return "[" + todos.map(todoJson).join(",") + "]"; +} + +export function jsonResponse(status: number, body: string): response { + return { + status: status, + contentType: "application/json; charset=utf-8", + body: body + }; +} + +export function textResponse(status: number, body: string): response { + return { + status: status, + contentType: "text/plain; charset=utf-8", + body: body + }; +} + +export function handleRequest(state: TodoModel_appState, req: request): [TodoModel_appState, response] { + let id = parseRoute(req.method, req.path); + if (typeof id !== "object") { + switch (id) { + case "ListJson" : + return [ + state, + { + status: 200, + contentType: "application/json; charset=utf-8", + body: todosJson(state.todos) + } + ]; + case "Create" : + let match = parseCreateBody(req.body); + let title = match[0].trim(); + if (title.length === 0) { + return [ + state, + { + status: 400, + contentType: "text/plain; charset=utf-8", + body: "empty title" + } + ]; + } + let next = TodoModel.addTodo(state, title, match[1]); + return [ + next, + { + status: 201, + contentType: "application/json; charset=utf-8", + body: todosJson(next.todos) + } + ]; + case "ToggleAll" : + let next$1 = TodoModel.toggleAll(state); + return [ + next$1, + { + status: 200, + contentType: "application/json; charset=utf-8", + body: todosJson(next$1.todos) + } + ]; + case "ClearCompleted" : + let next$2 = TodoModel.clearCompleted(state); + return [ + next$2, + { + status: 200, + contentType: "application/json; charset=utf-8", + body: todosJson(next$2.todos) + } + ]; + case "BadId" : + return [ + state, + { + status: 400, + contentType: "text/plain; charset=utf-8", + body: "bad id" + } + ]; + case "NotFound" : + return [ + state, + { + status: 404, + contentType: "text/plain; charset=utf-8", + body: "not found" + } + ]; + } + } else { + switch (id.TAG) { + case "Home" : + return [ + state, + { + status: 200, + contentType: "text/html; charset=utf-8", + body: TodoView.renderPage(state, id._0, id._1) + } + ]; + case "GetTodo" : + let todo = TodoModel.findTodo(state.todos, id._0); + if (todo !== undefined) { + return [ + state, + { + status: 200, + contentType: "application/json; charset=utf-8", + body: todoJson(todo) + } + ]; + } else { + return [ + state, + { + status: 404, + contentType: "text/plain; charset=utf-8", + body: "not found" + } + ]; + } + case "Toggle" : + let next$3 = TodoModel.toggleTodo(state, id._0); + return [ + next$3, + { + status: 200, + contentType: "application/json; charset=utf-8", + body: todosJson(next$3.todos) + } + ]; + case "Edit" : + let title$1 = req.body.trim(); + if (title$1.length === 0) { + return [ + state, + { + status: 400, + contentType: "text/plain; charset=utf-8", + body: "empty title" + } + ]; + } + let next$4 = TodoModel.editTodo(state, id._0, title$1); + return [ + next$4, + { + status: 200, + contentType: "application/json; charset=utf-8", + body: todosJson(next$4.todos) + } + ]; + case "CyclePriority" : + let next$5 = TodoModel.cyclePriority(state, id._0); + return [ + next$5, + { + status: 200, + contentType: "application/json; charset=utf-8", + body: todosJson(next$5.todos) + } + ]; + case "Delete" : + let next$6 = TodoModel.deleteTodo(state, id._0); + return [ + next$6, + { + status: 200, + contentType: "application/json; charset=utf-8", + body: todosJson(next$6.todos) + } + ]; + } + } +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/TodoModel.res b/tests/build_tests/emit_ts/src/TodoModel.res new file mode 100644 index 00000000000..c46e101cb9d --- /dev/null +++ b/tests/build_tests/emit_ts/src/TodoModel.res @@ -0,0 +1,171 @@ +type priority = Low | Medium | High + +type filter = All | Active | Completed + +type todo = { + id: int, + title: string, + done: bool, + priority: priority, +} + +type appState = { + nextId: int, + todos: array, +} + +type counts = { + total: int, + active: int, + completed: int, +} + +let initState = (): appState => { + nextId: 4, + todos: [ + { + id: 1, + title: "Compile ReScript modules with -bs-emit-ts", + done: true, + priority: High, + }, + { + id: 2, + title: "Verify every generated function with TScert", + done: true, + priority: High, + }, + { + id: 3, + title: "Add, filter, prioritize, or edit a task below", + done: false, + priority: Medium, + }, + ], +} + +let nextPriority = (p: priority): priority => + switch p { + | Low => Medium + | Medium => High + | High => Low + } + +let priorityFromString = (s: string): priority => + switch String.toLowerCase(String.trim(s)) { + | "high" => High + | "low" => Low + | _ => Medium + } + +let priorityToString = (p: priority): string => + switch p { + | Low => "low" + | Medium => "medium" + | High => "high" + } + +let filterFromString = (s: string): filter => + switch String.toLowerCase(String.trim(s)) { + | "active" => Active + | "completed" => Completed + | _ => All + } + +let filterToString = (f: filter): string => + switch f { + | All => "all" + | Active => "active" + | Completed => "completed" + } + +let addTodo = (state: appState, title: string, priority: priority): appState => { + let clean = String.trim(title) + if String.length(clean) == 0 { + state + } else { + let todo = { + id: state.nextId, + title: clean, + done: false, + priority, + } + let todos = Array.copy(state.todos) + Array.push(todos, todo) + {nextId: state.nextId + 1, todos} + } +} + +let toggleTodo = (state: appState, id: int): appState => { + let todos = Array.map(state.todos, t => t.id == id ? {...t, done: !t.done} : t) + {nextId: state.nextId, todos} +} + +let editTodo = (state: appState, id: int, title: string): appState => { + let clean = String.trim(title) + if String.length(clean) == 0 { + state + } else { + let todos = Array.map(state.todos, t => t.id == id ? {...t, title: clean} : t) + {nextId: state.nextId, todos} + } +} + +let cyclePriority = (state: appState, id: int): appState => { + let todos = Array.map(state.todos, t => + t.id == id ? {...t, priority: nextPriority(t.priority)} : t + ) + {nextId: state.nextId, todos} +} + +let deleteTodo = (state: appState, id: int): appState => { + let todos = Array.filter(state.todos, t => t.id != id) + {nextId: state.nextId, todos} +} + +let clearCompleted = (state: appState): appState => { + let todos = Array.filter(state.todos, t => !t.done) + {nextId: state.nextId, todos} +} + +let toggleAll = (state: appState): appState => { + let hasActive = Array.some(state.todos, t => !t.done) + let todos = Array.map(state.todos, t => {...t, done: hasActive}) + {nextId: state.nextId, todos} +} + +let visibleTodos = (todos: array, filter: filter, query: string): array => { + let q = String.toLowerCase(String.trim(query)) + Array.filter(todos, t => { + let matchesFilter = switch filter { + | All => true + | Active => !t.done + | Completed => t.done + } + let matchesQuery = String.length(q) == 0 || String.includes(String.toLowerCase(t.title), q) + matchesFilter && matchesQuery + }) +} + +let countTodos = (todos: array): counts => { + let active = ref(0) + let completed = ref(0) + for i in 0 to Array.length(todos) - 1 { + switch todos[i] { + | Some(t) => + if t.done { + completed := completed.contents + 1 + } else { + active := active.contents + 1 + } + | None => () + } + } + { + total: active.contents + completed.contents, + active: active.contents, + completed: completed.contents, + } +} + +let findTodo = (todos: array, id: int): option => Array.find(todos, t => t.id == id) diff --git a/tests/build_tests/emit_ts/src/TodoModel.res.ts b/tests/build_tests/emit_ts/src/TodoModel.res.ts new file mode 100644 index 00000000000..e07cb0b6c41 --- /dev/null +++ b/tests/build_tests/emit_ts/src/TodoModel.res.ts @@ -0,0 +1,265 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +export type priority = "Low" | "Medium" | "High"; + +export type filter = "All" | "Active" | "Completed"; + +export type todo = { + readonly id: number; + readonly title: string; + readonly done: boolean; + readonly priority: priority +}; + +export type appState = { readonly nextId: number; readonly todos: todo[] }; + +export type counts = { + readonly total: number; + readonly active: number; + readonly completed: number +}; + +export function initState(): appState { + return { + nextId: 4, + todos: [ + { + id: 1, + title: "Compile ReScript modules with -bs-emit-ts", + done: true, + priority: "High" + }, + { + id: 2, + title: "Verify every generated function with TScert", + done: true, + priority: "High" + }, + { + id: 3, + title: "Add, filter, prioritize, or edit a task below", + done: false, + priority: "Medium" + } + ] + }; +} + +export function nextPriority(p: priority): priority { + switch (p) { + case "Low" : + return "Medium"; + case "Medium" : + return "High"; + case "High" : + return "Low"; + } +} + +export function priorityFromString(s: string): priority { + let match = s.trim().toLowerCase(); + switch (match) { + case "high" : + return "High"; + case "low" : + return "Low"; + default: + return "Medium"; + } +} + +export function priorityToString(p: priority): string { + switch (p) { + case "Low" : + return "low"; + case "Medium" : + return "medium"; + case "High" : + return "high"; + } +} + +export function filterFromString(s: string): filter { + let match = s.trim().toLowerCase(); + switch (match) { + case "active" : + return "Active"; + case "completed" : + return "Completed"; + default: + return "All"; + } +} + +export function filterToString(f: filter): string { + switch (f) { + case "All" : + return "all"; + case "Active" : + return "active"; + case "Completed" : + return "completed"; + } +} + +export function addTodo(state: appState, title: string, priority: priority): appState { + let clean = title.trim(); + if (clean.length === 0) { + return state; + } + let todo_id = state.nextId; + let todo = { + id: todo_id, + title: clean, + done: false, + priority: priority + }; + let todos = state.todos.slice(); + todos.push(todo); + return { + nextId: state.nextId + 1 | 0, + todos: todos + }; +} + +export function toggleTodo(state: appState, id: number): appState { + let todos = state.todos.map(t => { + if (t.id === id) { + return { + id: t.id, + title: t.title, + done: !t.done, + priority: t.priority + }; + } else { + return t; + } + }); + return { + nextId: state.nextId, + todos: todos + }; +} + +export function editTodo(state: appState, id: number, title: string): appState { + let clean = title.trim(); + if (clean.length === 0) { + return state; + } + let todos = state.todos.map(t => { + if (t.id === id) { + return { + id: t.id, + title: clean, + done: t.done, + priority: t.priority + }; + } else { + return t; + } + }); + return { + nextId: state.nextId, + todos: todos + }; +} + +export function cyclePriority(state: appState, id: number): appState { + let todos = state.todos.map(t => { + if (t.id === id) { + return { + id: t.id, + title: t.title, + done: t.done, + priority: nextPriority(t.priority) + }; + } else { + return t; + } + }); + return { + nextId: state.nextId, + todos: todos + }; +} + +export function deleteTodo(state: appState, id: number): appState { + let todos = state.todos.filter(t => t.id !== id); + return { + nextId: state.nextId, + todos: todos + }; +} + +export function clearCompleted(state: appState): appState { + let todos = state.todos.filter(t => !t.done); + return { + nextId: state.nextId, + todos: todos + }; +} + +export function toggleAll(state: appState): appState { + let hasActive = state.todos.some(t => !t.done); + let todos = state.todos.map(t => ({ + id: t.id, + title: t.title, + done: hasActive, + priority: t.priority + })); + return { + nextId: state.nextId, + todos: todos + }; +} + +export function visibleTodos(todos: todo[], filter: filter, query: string): todo[] { + let q = query.trim().toLowerCase(); + return todos.filter(t => { + let matchesFilter: boolean; + switch (filter) { + case "All" : + matchesFilter = true; + break; + case "Active" : + matchesFilter = !t.done; + break; + case "Completed" : + matchesFilter = t.done; + break; + } + let matchesQuery = q.length === 0 || t.title.toLowerCase().includes(q); + if (matchesFilter) { + return matchesQuery; + } else { + return false; + } + }); +} + +export function countTodos(todos: todo[]): counts { + let active: number = 0; + let completed: number = 0; + for (let i = 0, i_finish = todos.length; i < i_finish; ++i) { + let t = todos[i]; + if (t !== undefined) { + if (t.done) { + completed = completed + 1 | 0; + } else { + active = active + 1 | 0; + } + } + } + return { + total: active + completed | 0, + active: active, + completed: completed + }; +} + +export function findTodo(todos: todo[], id: number): (undefined | todo) { + return todos.find(t => t.id === id); +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/src/TodoView.res b/tests/build_tests/emit_ts/src/TodoView.res new file mode 100644 index 00000000000..b20e4be7ec5 --- /dev/null +++ b/tests/build_tests/emit_ts/src/TodoView.res @@ -0,0 +1,413 @@ +let escapeHtml = (text: string): string => { + let out = ref("") + for i in 0 to String.length(text) - 1 { + let c = String.charAt(text, i) + let escaped = switch c { + | "&" => "&" + | "<" => "<" + | ">" => ">" + | "\"" => """ + | "'" => "'" + | _ => c + } + out := out.contents ++ escaped + } + out.contents +} + +let priorityLabel = (p: TodoModel.priority): string => + switch p { + | Low => "Low" + | Medium => "Med" + | High => "High" + } + +let priorityClass = (p: TodoModel.priority): string => + switch p { + | Low => "prio-low" + | Medium => "prio-med" + | High => "prio-high" + } + +let renderTodoItem = (t: TodoModel.todo): string => { + let idStr = Int.toString(t.id) + let rowClass = t.done ? "todo-item is-done" : "todo-item" + let checkMark = t.done ? "✓" : "" + let titleEsc = escapeHtml(t.title) + let prioCls = priorityClass(t.priority) + let prioLbl = priorityLabel(t.priority) + "
  • " ++ + "" ++ + "" ++ + titleEsc ++ + "" ++ + "" ++ + "" ++ + "" ++ "
  • " +} + +let renderFilterTab = ( + label: string, + count: int, + target: TodoModel.filter, + current: TodoModel.filter, + query: string, +): string => { + let activeCls = target == current ? "tab is-active" : "tab" + let fStr = TodoModel.filterToString(target) + let qPart = + String.length(String.trim(query)) > 0 ? "&q=" ++ escapeHtml(String.trim(query)) : "" + "
    " ++ + label ++ + " " ++ + Int.toString(count) ++ "" +} + +let styles = ` + :root { + --bg: #f4f5f7; + --card: #ffffff; + --text: #111827; + --muted: #6b7280; + --border: #e5e7eb; + --accent: #e6484f; + --accent-hover: #cf353c; + --done: #10b981; + } + * { box-sizing: border-box; } + body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + background: var(--bg); + color: var(--text); + min-height: 100vh; + padding: 36px 16px; + } + .shell { + max-width: 640px; + margin: 0 auto; + } + .header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 16px; + gap: 12px; + } + .header h1 { + margin: 0; + font-size: 26px; + font-weight: 700; + letter-spacing: -0.02em; + } + .badge { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + font-weight: 600; + color: #065f46; + background: #d1fae5; + border: 1px solid #a7f3d0; + padding: 4px 10px; + border-radius: 999px; + white-space: nowrap; + } + .card { + background: var(--card); + border: 1px solid var(--border); + border-radius: 14px; + box-shadow: 0 8px 24px rgba(17, 24, 39, 0.06); + overflow: hidden; + } + .add-form { + display: flex; + gap: 8px; + padding: 16px; + border-bottom: 1px solid var(--border); + background: #fcfcfd; + } + .add-input { + flex: 1; + font-size: 15px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: 8px; + outline: none; + } + .add-input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(230,72,79,0.12); } + .prio-select { + font-size: 13px; + padding: 0 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: #fff; + color: var(--text); + } + .add-btn { + background: var(--accent); + color: #fff; + border: none; + border-radius: 8px; + padding: 0 16px; + font-size: 14px; + font-weight: 600; + cursor: pointer; + } + .add-btn:hover { background: var(--accent-hover); } + .toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 12px 16px; + border-bottom: 1px solid var(--border); + } + .tabs { display: flex; gap: 6px; } + .tab { + text-decoration: none; + color: var(--muted); + font-size: 13px; + font-weight: 500; + padding: 5px 10px; + border-radius: 7px; + } + .tab:hover { background: #f3f4f6; color: var(--text); } + .tab.is-active { background: #111827; color: #fff; } + .tab-count { + font-size: 11px; + opacity: 0.75; + margin-left: 2px; + } + .search-form { display: flex; gap: 6px; align-items: center; } + .search-input { + font-size: 13px; + padding: 5px 10px; + border: 1px solid var(--border); + border-radius: 7px; + width: 160px; + outline: none; + } + .search-input:focus { border-color: #9ca3af; } + .todo-list { + list-style: none; + margin: 0; + padding: 0; + } + .todo-item { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + border-bottom: 1px solid var(--border); + transition: background 0.1s ease; + } + .todo-item:hover { background: #fafafa; } + .todo-item:last-child { border-bottom: none; } + .check-btn { + width: 22px; + height: 22px; + border-radius: 6px; + border: 2px solid #d1d5db; + background: #fff; + color: #fff; + font-size: 13px; + font-weight: 700; + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + flex-shrink: 0; + } + .todo-item.is-done .check-btn { + background: var(--done); + border-color: var(--done); + } + .todo-title { + flex: 1; + font-size: 15px; + line-height: 1.4; + word-break: break-word; + } + .todo-item.is-done .todo-title { + text-decoration: line-through; + color: var(--muted); + } + .prio-pill { + font-size: 11px; + font-weight: 600; + padding: 3px 8px; + border-radius: 999px; + border: none; + cursor: pointer; + flex-shrink: 0; + } + .prio-low { background: #e5e7eb; color: #374151; } + .prio-med { background: #fef3c7; color: #92400e; } + .prio-high { background: #fee2e2; color: #991b1b; } + .icon-btn { + border: none; + background: transparent; + color: #9ca3af; + font-size: 14px; + width: 28px; + height: 28px; + border-radius: 6px; + cursor: pointer; + flex-shrink: 0; + } + .icon-btn:hover { background: #f3f4f6; color: var(--text); } + .del-btn:hover { background: #fee2e2; color: #b91c1c; } + .empty { + padding: 36px 16px; + text-align: center; + color: var(--muted); + font-size: 14px; + } + .footer { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 16px; + border-top: 1px solid var(--border); + background: #fcfcfd; + font-size: 13px; + color: var(--muted); + } + .footer-actions { display: flex; gap: 8px; } + .ghost-btn { + border: 1px solid var(--border); + background: #fff; + color: var(--text); + font-size: 12px; + font-weight: 500; + padding: 5px 10px; + border-radius: 7px; + cursor: pointer; + } + .ghost-btn:hover { background: #f3f4f6; } + .note { + margin-top: 14px; + text-align: center; + font-size: 12px; + color: var(--muted); + } +` + +let clientScript = ` + function addItem(e) { + e.preventDefault(); + var input = document.getElementById("new-title"); + var prio = document.getElementById("new-prio").value; + var title = input.value.trim(); + if (!title) return; + fetch("/todos", { method: "POST", body: prio + "|" + title }).then(function () { + location.reload(); + }); + } + function post(url, body) { + fetch(url, { method: "POST", body: body || "" }).then(function () { + location.reload(); + }); + } + function del(url) { + fetch(url, { method: "DELETE" }).then(function () { + location.reload(); + }); + } + function editItem(id, span) { + var next = prompt("Edit task title:", span.textContent || ""); + if (next !== null && next.trim().length > 0) { + post("/todos/" + id + "/edit", next.trim()); + } + } + function editFromBtn(id, btn) { + var li = btn.closest("li"); + var span = li && li.querySelector(".todo-title"); + if (span) editItem(id, span); + } +` + +let renderPage = (state: TodoModel.appState, filter: TodoModel.filter, query: string): string => { + let counts = TodoModel.countTodos(state.todos) + let shown = TodoModel.visibleTodos(state.todos, filter, query) + let listBody = if Array.length(shown) == 0 { + "
    No tasks match this view.
    " + } else { + "
      " ++ Array.join(Array.map(shown, renderTodoItem), "") ++ "
    " + } + let tabs = + renderFilterTab("All", counts.total, All, filter, query) ++ + renderFilterTab("Active", counts.active, Active, filter, query) ++ + renderFilterTab("Completed", counts.completed, Completed, filter, query) + let itemWord = counts.active == 1 ? "item" : "items" + let qEsc = escapeHtml(String.trim(query)) + let filterInput = + "" + "" ++ + "" ++ + "ReScript + TScert Todo
    " ++ + "

    Tasks

    " ++ + "✓ ReScript → TScert verified
    " ++ + "
    " ++ + "
    " ++ + "" ++ + "" ++ + "" ++ + "
    " ++ + "
    " ++ + "" ++ + "
    " ++ + filterInput ++ + "" ++ + "
    " ++ + "
    " ++ + listBody ++ + "
    " ++ + "" ++ + Int.toString(counts.active) ++ + " " ++ + itemWord ++ + " left" ++ + "
    " ++ + "" ++ + "" ++ + "
    " ++ + "

    Double-click a task to edit · Click priority pill to cycle · Pure ReScript core verified by TScert

    " ++ + "
    " +} diff --git a/tests/build_tests/emit_ts/src/TodoView.res.ts b/tests/build_tests/emit_ts/src/TodoView.res.ts new file mode 100644 index 00000000000..8de7ced81a2 --- /dev/null +++ b/tests/build_tests/emit_ts/src/TodoView.res.ts @@ -0,0 +1,360 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as TodoModel from "./TodoModel.res.ts"; + +import type {appState as TodoModel_appState} from './TodoModel.res.ts'; + +import type {counts as TodoModel_counts} from './TodoModel.res.ts'; + +import type {filter as TodoModel_filter} from './TodoModel.res.ts'; + +import type {priority as TodoModel_priority} from './TodoModel.res.ts'; + +import type {todo as TodoModel_todo} from './TodoModel.res.ts'; + +export function escapeHtml(text: string): string { + let out: string = ""; + for (let i = 0, i_finish = text.length; i < i_finish; ++i) { + let c = text.charAt(i); + let escaped: string; + switch (c) { + case "\"" : + escaped = """; + break; + case "&" : + escaped = "&"; + break; + case "'" : + escaped = "'"; + break; + case "<" : + escaped = "<"; + break; + case ">" : + escaped = ">"; + break; + default: + escaped = c; + } + out = out + escaped; + } + return out; +} + +export function priorityLabel(p: TodoModel_priority): string { + switch (p) { + case "Low" : + return "Low"; + case "Medium" : + return "Med"; + case "High" : + return "High"; + } +} + +export function priorityClass(p: TodoModel_priority): string { + switch (p) { + case "Low" : + return "prio-low"; + case "Medium" : + return "prio-med"; + case "High" : + return "prio-high"; + } +} + +export function renderTodoItem(t: TodoModel_todo): string { + let idStr = t.id.toString(); + let rowClass = t.done ? "todo-item is-done" : "todo-item"; + let checkMark = t.done ? "✓" : ""; + let titleEsc = escapeHtml(t.title); + let prioCls = priorityClass(t.priority); + let prioLbl = priorityLabel(t.priority); + return "
  • " + titleEsc + "
  • "; +} + +export function renderFilterTab(label: string, count: number, target: TodoModel_filter, current: TodoModel_filter, query: string): string { + let activeCls = target === current ? "tab is-active" : "tab"; + let fStr = TodoModel.filterToString(target); + let qPart = query.trim().length > 0 ? "&q=" + escapeHtml(query.trim()) : ""; + return "" + label + " " + count.toString() + ""; +} + +export const styles: string = ` + :root { + --bg: #f4f5f7; + --card: #ffffff; + --text: #111827; + --muted: #6b7280; + --border: #e5e7eb; + --accent: #e6484f; + --accent-hover: #cf353c; + --done: #10b981; + } + * { box-sizing: border-box; } + body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + background: var(--bg); + color: var(--text); + min-height: 100vh; + padding: 36px 16px; + } + .shell { + max-width: 640px; + margin: 0 auto; + } + .header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 16px; + gap: 12px; + } + .header h1 { + margin: 0; + font-size: 26px; + font-weight: 700; + letter-spacing: -0.02em; + } + .badge { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + font-weight: 600; + color: #065f46; + background: #d1fae5; + border: 1px solid #a7f3d0; + padding: 4px 10px; + border-radius: 999px; + white-space: nowrap; + } + .card { + background: var(--card); + border: 1px solid var(--border); + border-radius: 14px; + box-shadow: 0 8px 24px rgba(17, 24, 39, 0.06); + overflow: hidden; + } + .add-form { + display: flex; + gap: 8px; + padding: 16px; + border-bottom: 1px solid var(--border); + background: #fcfcfd; + } + .add-input { + flex: 1; + font-size: 15px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: 8px; + outline: none; + } + .add-input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(230,72,79,0.12); } + .prio-select { + font-size: 13px; + padding: 0 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: #fff; + color: var(--text); + } + .add-btn { + background: var(--accent); + color: #fff; + border: none; + border-radius: 8px; + padding: 0 16px; + font-size: 14px; + font-weight: 600; + cursor: pointer; + } + .add-btn:hover { background: var(--accent-hover); } + .toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 12px 16px; + border-bottom: 1px solid var(--border); + } + .tabs { display: flex; gap: 6px; } + .tab { + text-decoration: none; + color: var(--muted); + font-size: 13px; + font-weight: 500; + padding: 5px 10px; + border-radius: 7px; + } + .tab:hover { background: #f3f4f6; color: var(--text); } + .tab.is-active { background: #111827; color: #fff; } + .tab-count { + font-size: 11px; + opacity: 0.75; + margin-left: 2px; + } + .search-form { display: flex; gap: 6px; align-items: center; } + .search-input { + font-size: 13px; + padding: 5px 10px; + border: 1px solid var(--border); + border-radius: 7px; + width: 160px; + outline: none; + } + .search-input:focus { border-color: #9ca3af; } + .todo-list { + list-style: none; + margin: 0; + padding: 0; + } + .todo-item { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + border-bottom: 1px solid var(--border); + transition: background 0.1s ease; + } + .todo-item:hover { background: #fafafa; } + .todo-item:last-child { border-bottom: none; } + .check-btn { + width: 22px; + height: 22px; + border-radius: 6px; + border: 2px solid #d1d5db; + background: #fff; + color: #fff; + font-size: 13px; + font-weight: 700; + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + flex-shrink: 0; + } + .todo-item.is-done .check-btn { + background: var(--done); + border-color: var(--done); + } + .todo-title { + flex: 1; + font-size: 15px; + line-height: 1.4; + word-break: break-word; + } + .todo-item.is-done .todo-title { + text-decoration: line-through; + color: var(--muted); + } + .prio-pill { + font-size: 11px; + font-weight: 600; + padding: 3px 8px; + border-radius: 999px; + border: none; + cursor: pointer; + flex-shrink: 0; + } + .prio-low { background: #e5e7eb; color: #374151; } + .prio-med { background: #fef3c7; color: #92400e; } + .prio-high { background: #fee2e2; color: #991b1b; } + .icon-btn { + border: none; + background: transparent; + color: #9ca3af; + font-size: 14px; + width: 28px; + height: 28px; + border-radius: 6px; + cursor: pointer; + flex-shrink: 0; + } + .icon-btn:hover { background: #f3f4f6; color: var(--text); } + .del-btn:hover { background: #fee2e2; color: #b91c1c; } + .empty { + padding: 36px 16px; + text-align: center; + color: var(--muted); + font-size: 14px; + } + .footer { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 16px; + border-top: 1px solid var(--border); + background: #fcfcfd; + font-size: 13px; + color: var(--muted); + } + .footer-actions { display: flex; gap: 8px; } + .ghost-btn { + border: 1px solid var(--border); + background: #fff; + color: var(--text); + font-size: 12px; + font-weight: 500; + padding: 5px 10px; + border-radius: 7px; + cursor: pointer; + } + .ghost-btn:hover { background: #f3f4f6; } + .note { + margin-top: 14px; + text-align: center; + font-size: 12px; + color: var(--muted); + } +`; + +export const clientScript: string = ` + function addItem(e) { + e.preventDefault(); + var input = document.getElementById("new-title"); + var prio = document.getElementById("new-prio").value; + var title = input.value.trim(); + if (!title) return; + fetch("/todos", { method: "POST", body: prio + "|" + title }).then(function () { + location.reload(); + }); + } + function post(url, body) { + fetch(url, { method: "POST", body: body || "" }).then(function () { + location.reload(); + }); + } + function del(url) { + fetch(url, { method: "DELETE" }).then(function () { + location.reload(); + }); + } + function editItem(id, span) { + var next = prompt("Edit task title:", span.textContent || ""); + if (next !== null && next.trim().length > 0) { + post("/todos/" + id + "/edit", next.trim()); + } + } + function editFromBtn(id, btn) { + var li = btn.closest("li"); + var span = li && li.querySelector(".todo-title"); + if (span) editItem(id, span); + } +`; + +export function renderPage(state: TodoModel_appState, filter: TodoModel_filter, query: string): string { + let counts = TodoModel.countTodos(state.todos); + let shown = TodoModel.visibleTodos(state.todos, filter, query); + let listBody = shown.length === 0 ? "
    No tasks match this view.
    " : "
      " + shown.map(renderTodoItem).join("") + "
    "; + let tabs = renderFilterTab("All", counts.total, "All", filter, query) + renderFilterTab("Active", counts.active, "Active", filter, query) + renderFilterTab("Completed", counts.completed, "Completed", filter, query); + let itemWord = counts.active === 1 ? "item" : "items"; + let qEsc = escapeHtml(query.trim()); + let filterInput = ""; + return "ReScript + TScert Todo

    Tasks

    ✓ ReScript → TScert verified
    " + filterInput + "
    " + listBody + "
    " + counts.active.toString() + " " + itemWord + " left

    Double-click a task to edit · Click priority pill to cycle · Pure ReScript core verified by TScert

    "; +} + +/* No side effect */ diff --git a/tests/build_tests/emit_ts/todo-server.mts b/tests/build_tests/emit_ts/todo-server.mts new file mode 100644 index 00000000000..afb2bf508e2 --- /dev/null +++ b/tests/build_tests/emit_ts/todo-server.mts @@ -0,0 +1,34 @@ +// Thin Node HTTP adapter around the TScert-verified ReScript modules +// (src/TodoModel.res.ts, src/TodoView.res.ts, src/TodoApp.res.ts). +// This file is not part of the verified core. Run with Node >= 23.6: +// +// node tests/build_tests/emit_ts/todo-server.mts + +import { createServer } from "node:http"; +import { initState } from "./src/TodoModel.res.ts"; +import { handleRequest } from "./src/TodoApp.res.ts"; + +let state = initState(); + +const server = createServer((req, res) => { + let body = ""; + req.on("data", (chunk: Buffer) => { + body += chunk.toString("utf8"); + }); + req.on("end", () => { + const [next, response] = handleRequest(state, { + method: req.method ?? "GET", + path: req.url ?? "/", + body, + }); + state = next; + res.writeHead(response.status, { "content-type": response.contentType }); + res.end(response.body); + }); +}); + +const port = Number(process.env.PORT ?? 8080); + +server.listen(port, "127.0.0.1", () => { + console.log(`ReScript + TScert todo app listening on http://127.0.0.1:${port}`); +});