Skip to content

Commit

Permalink
Add [@@@js.require]
Browse files Browse the repository at this point in the history
  • Loading branch information
nojb committed Jun 2, 2024
1 parent 05c937b commit 6f76172
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
16 changes: 16 additions & 0 deletions VALUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,22 @@ For instance, the following annotated modules will generate the same code:
end [@js.scope "inner"] [@js.scope "outer"]
```

Require
-------

The signature attribute `[@@@js.require "name"]` is equivalent to making the
current global object the result of `require("name")`. This is useful to bind
Node libraries. For instance,

```ocaml
module[@js.require "crypto"] C: sig
type hash
val create_hash: unit -> hash [@@js.global]
end
```

will bind the `createHash` function of the Node library `crypto`.

First-class modules
-------------------

Expand Down
11 changes: 11 additions & 0 deletions examples/test/test_bindings.mli
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,14 @@ end
module Dict : sig
type t = { h : ((string * int) list [@js.dict]) }
end

module X : sig
[@@@js.require "foo"]

val x : int -> int [@@js.global]
val y : string [@@js.global]
end

module[@js.require "crypto"] Crypto : sig
val z : int [@@js.global]
end
10 changes: 8 additions & 2 deletions ppx-lib/gen_js_api_ppx.ml
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,9 @@ let ojs_set o s v =
else
ojs "set_prop" [o; ojs "string_to_js" [str s]; v]

let node_require e =
ojs "apply" [ojs "variable" [str "require"]; Exp.array [ojs "string_to_js" [e]]]

let select_path o s =
let rec select_path o = function
| [] -> assert false
Expand Down Expand Up @@ -1605,13 +1608,16 @@ let process_fields ctx ~global_attrs l =
jsname, (* JS name *)
parse_typ ctx ~global_attrs typ


let global_object ~global_attrs =
let rec traverse = function
| [] -> ojs_global
| hd :: tl ->
begin match get_expr_attribute "js.scope" [hd] with
| None -> traverse tl
| None ->
begin match get_expr_attribute "js.require" [hd] with
| None -> traverse tl
| Some exp -> node_require exp
end
| Some {pexp_desc=Pexp_constant (Pconst_string (prop, _, _)); _} -> ojs_get (traverse tl) prop
| Some {pexp_desc=Pexp_tuple path; _} ->
let init = traverse tl in
Expand Down

0 comments on commit 6f76172

Please sign in to comment.