Skip to content

Commit 702a5cd

Browse files
authored
Transform Pexp_function with browser_only (#146)
1 parent 38373ea commit 702a5cd

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

packages/browser-ppx/ppx.ml

+11
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,17 @@ module Browser_only = struct
247247
in
248248
let item = { fn with pexp_attributes = expr.pexp_attributes } in
249249
make_vb_with_browser_only ~loc pattern item
250+
| Pexp_function _cases ->
251+
(* Because pexp_function doesn't have a pattern, neither a label, we construct an empty pattern and use it to generate the vb *)
252+
let original_function_name = get_function_name pattern.ppat_desc in
253+
let fn =
254+
Builder.pexp_fun ~loc Nolabel None
255+
[%pat? _]
256+
(last_expr_to_raise_impossible ~loc original_function_name
257+
expression)
258+
in
259+
let item = { fn with pexp_attributes = expression.pexp_attributes } in
260+
make_vb_with_browser_only ~loc pattern item
250261
| Pexp_ident { txt = _longident; loc } ->
251262
let item = [%expr Obj.magic ()] in
252263
make_vb_with_browser_only ~loc pattern item
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
$ cat > input.re << EOF
2+
> let%browser_only foo = fun
3+
> | x when x < 0. => None
4+
> | x => Some("bar");
5+
>
6+
> let make = () => {
7+
> let%browser_only foo = fun
8+
> | x when x < 0. => None
9+
> | x => Some("bar");
10+
> ();
11+
> };
12+
> EOF
13+
14+
$ refmt --parse re --print ml input.re > input.ml
15+
16+
With -js flag everything keeps as it is and browser_only extension disappears
17+
18+
$ ./standalone.exe -impl input.ml -js | ocamlformat - --enable-outside-detected-project --impl
19+
let foo = function x when x < 0. -> None | x -> Some "bar" [@explicit_arity]
20+
21+
let make () =
22+
let foo = function
23+
| x when x < 0. -> None
24+
| x -> Some "bar" [@explicit_arity]
25+
in
26+
()
27+
28+
Without -js flag, the compilation to native errors out indicating that a function must be used
29+
30+
$ ./standalone.exe -impl input.ml | ocamlformat - --enable-outside-detected-project --impl
31+
let (foo
32+
[@alert
33+
browser_only
34+
"This expression is marked to only run on the browser where JavaScript \
35+
can run. You can only use it inside a let%browser_only function."]) =
36+
fun [@alert "-browser_only"] _ -> Runtime.fail_impossible_action_in_ssr "foo"
37+
[@@warning "-27-32"]
38+
39+
let make () =
40+
let foo =
41+
[%ocaml.error
42+
"[browser_ppx] browser_only works on function definitions. For other \
43+
cases, use switch%platform or feel free to open an issue in \
44+
https://github.com/ml-in-barcelona/server-reason-react."]
45+
in
46+
()

0 commit comments

Comments
 (0)