Source file ppx.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
open Ppxlib
open Ast_builder.Default
module List = ListLabels
let issues_url = "https://github.com/davesnx/html_of_jsx/issues"
let disable_static_optimization = ref false
let pexp_list ~loc xs =
List.fold_left (List.rev xs) ~init:[%expr []] ~f:(fun xs x ->
[%expr [%e x] :: [%e xs]])
exception Error of expression
let raise_errorf ~loc fmt =
let open Ast_builder.Default in
Printf.ksprintf
(fun msg ->
let expr =
pexp_extension ~loc
(Location.error_extensionf ~loc "[html_of_jsx] %s" msg)
in
raise (Error expr))
fmt
let rec unwrap_children ~f children = function
| { pexp_desc = Pexp_construct ({ txt = Lident "[]"; _ }, None); _ } ->
List.rev children
| {
pexp_desc =
Pexp_construct
( { txt = Lident "::"; _ },
Some { pexp_desc = Pexp_tuple [ child; next ]; _ } );
_;
} ->
unwrap_children ~f (f child :: children) next
| e -> raise_errorf ~loc:e.pexp_loc "children prop should be a list"
let is_jsx = function
| { attr_name = { txt = "JSX"; _ }; _ } -> true
| _ -> false
let has_jsx_attr attrs = List.exists ~f:is_jsx attrs
let rewrite_component ~loc tag args children =
let component = pexp_ident ~loc tag in
let props =
match children with
| None -> args
| Some [ children ] -> (Labelled "children", children) :: args
| Some children ->
(Labelled "children", [%expr [%e pexp_list ~loc children]]) :: args
in
pexp_apply ~loc component props
let validate_attr ~loc id name =
match Html.findByName id name with
| Ok p -> p
| Error `ElementNotFound ->
raise_errorf ~loc
{|HTML tag '%s' doesn't exist.
If this is not correct, please open an issue at %s|}
id issues_url
| Error (`AttributeNotFound suggestion) ->
let suggestion =
match suggestion with
| Some suggestion ->
Printf.sprintf "Hint: Maybe you mean '%s'?\n" suggestion
| None -> ""
in
raise_errorf ~loc
{|The attribute '%s' is not valid on a '%s' element.
%s
If this is not correct, please open an issue at %s.|}
name id suggestion issues_url
let add_attribute_type_constraint ~loc ~is_optional
(type_ : Html_attributes.kind) value =
match (type_, is_optional) with
| String, true -> [%expr ([%e value] : string option)]
| String, false -> [%expr ([%e value] : string)]
| Int, false -> [%expr ([%e value] : int)]
| Int, true -> [%expr ([%e value] : int option)]
| Bool, false -> [%expr ([%e value] : bool)]
| Bool, true -> [%expr ([%e value] : bool option)]
| BooleanishString, false -> [%expr ([%e value] : bool)]
| BooleanishString, true -> [%expr ([%e value] : bool option)]
| Style, false -> [%expr ([%e value] : string)]
| Style, true -> [%expr ([%e value] : string option)]
let make_attribute ~loc ~is_optional ~prop attribute_name attribute_value =
let open Html_attributes in
match (prop, is_optional) with
| Rich_attribute { type_ = String; _ }, false
| Attribute { type_ = String; _ }, false ->
[%expr Some ([%e attribute_name], `String [%e attribute_value])]
| Rich_attribute { type_ = String; _ }, true
| Attribute { type_ = String; _ }, true ->
[%expr
Stdlib.Option.map
(fun v -> ([%e attribute_name], `String v))
[%e attribute_value]]
| Rich_attribute { type_ = Int; _ }, false
| Attribute { type_ = Int; _ }, false ->
[%expr Some ([%e attribute_name], `Int [%e attribute_value])]
| Rich_attribute { type_ = Int; _ }, true | Attribute { type_ = Int; _ }, true
->
[%expr
Stdlib.Option.map
(fun v -> ([%e attribute_name], `Int v))
[%e attribute_value]]
| Rich_attribute { type_ = Bool; _ }, false
| Attribute { type_ = Bool; _ }, false ->
[%expr Some ([%e attribute_name], `Bool [%e attribute_value])]
| Rich_attribute { type_ = Bool; _ }, true
| Attribute { type_ = Bool; _ }, true ->
[%expr
Stdlib.Option.map
(fun v -> ([%e attribute_name], `Bool v))
[%e attribute_value]]
| Rich_attribute { type_ = BooleanishString; _ }, false
| Attribute { type_ = BooleanishString; _ }, false ->
[%expr
Some ([%e attribute_name], `String (Bool.to_string [%e attribute_value]))]
| Rich_attribute { type_ = BooleanishString; _ }, true
| Attribute { type_ = BooleanishString; _ }, true ->
[%expr
Stdlib.Option.map
(fun v -> ([%e attribute_name], `String v))
(Bool.to_string [%e attribute_value])]
| Rich_attribute { type_ = Style; _ }, false
| Attribute { type_ = Style; _ }, false ->
[%expr Some ("style", `String [%e attribute_value])]
| Rich_attribute { type_ = Style; _ }, true
| Attribute { type_ = Style; _ }, true ->
[%expr
Stdlib.Option.map (fun v -> ("style", `String v)) [%e attribute_value]]
| Event _, false ->
[%expr Some ([%e attribute_name], `String [%e attribute_value])]
| Event _, true ->
[%expr
Stdlib.Option.map
(fun v -> ([%e attribute_name], `String v))
[%e attribute_value]]
let is_optional = function Optional _ -> true | _ -> false
let transform_labelled ~loc:_parentLoc ~tag_name props (prop_label, value) =
let loc = props.pexp_loc in
match prop_label with
| Nolabel -> props
| Optional name | Labelled name ->
let is_optional = is_optional prop_label in
let attribute = validate_attr ~loc tag_name name in
let attribute_type =
match attribute with
| Rich_attribute { type_; _ } -> type_
| Attribute { type_; _ } -> type_
| Event _ -> String
in
let attribute_name = Html.getName attribute in
let attribute_name_expr = estring ~loc attribute_name in
let attribute_value =
add_attribute_type_constraint ~loc ~is_optional attribute_type value
in
let attribute_final =
make_attribute ~loc ~is_optional ~prop:attribute attribute_name_expr
attribute_value
in
[%expr [%e attribute_final] :: [%e props]]
let transform_attributes ~loc ~tag_name attrs =
let attrs =
List.rev attrs
|> List.fold_left ~f:(transform_labelled ~loc ~tag_name) ~init:[%expr []]
in
match attrs with
| [%expr []] -> [%expr []]
| attrs ->
[%expr Stdlib.List.filter_map Stdlib.Fun.id [%e attrs]]
(** Estimate buffer size based on static content and number of dynamic parts.
Static parts: exact length known at compile time Dynamic parts: estimate ~64
bytes each (reasonable for typical element content), int/float ~16 bytes *)
let estimate_buffer_size parts =
let static_size, dynamic_count =
List.fold_left parts ~init:(0, 0) ~f:(fun (static, dynamic) part ->
match part with
| Static_analysis.Static_str s -> (static + String.length s, dynamic)
| Static_analysis.Dynamic_string _ -> (static, dynamic + 1)
| Static_analysis.Dynamic_int _ -> (static + 16, dynamic)
| Static_analysis.Dynamic_float _ -> (static + 16, dynamic)
| Static_analysis.Dynamic_element _ -> (static, dynamic + 1))
in
let estimated = static_size + (dynamic_count * 64) in
let rec next_power_of_2 n acc =
if acc >= n then acc else next_power_of_2 n (acc * 2)
in
max 64 (next_power_of_2 estimated 64)
let generate_buffer_code ~loc parts =
let buf_var = "__html_buf" in
let buf_ident = pexp_ident ~loc { loc; txt = Lident buf_var } in
let buf_pat = ppat_var ~loc { loc; txt = buf_var } in
let buffer_size = estimate_buffer_size parts in
let buffer_size_expr = eint ~loc buffer_size in
let generate_part_code part =
match part with
| Static_analysis.Static_str s ->
let s_expr = estring ~loc s in
[%expr Buffer.add_string [%e buf_ident] [%e s_expr]]
| Static_analysis.Dynamic_string expr ->
[%expr Buffer.add_string [%e buf_ident] (JSX.escape [%e expr])]
| Static_analysis.Dynamic_int expr ->
[%expr Buffer.add_string [%e buf_ident] (Int.to_string [%e expr])]
| Static_analysis.Dynamic_float expr ->
[%expr Buffer.add_string [%e buf_ident] (Float.to_string [%e expr])]
| Static_analysis.Dynamic_element expr ->
[%expr JSX.write [%e buf_ident] [%e expr]]
in
let ops = List.map ~f:generate_part_code parts in
let seq =
List.fold_right ops ~init:[%expr ()] ~f:(fun op acc ->
[%expr
[%e op];
[%e acc]])
in
[%expr
let [%p buf_pat] = Buffer.create [%e buffer_size_expr] in
[%e seq];
JSX.unsafe (Buffer.contents [%e buf_ident])]
let rewrite_node_unoptimized ~loc tag_name args children =
let dom_node_name = estring ~loc tag_name in
let attributes = transform_attributes ~loc ~tag_name args in
match children with
| Some children ->
let childrens = pexp_list ~loc children in
[%expr JSX.node [%e dom_node_name] [%e attributes] [%e childrens]]
| None -> [%expr JSX.node [%e dom_node_name] [%e attributes] []]
let rewrite_node_optimized ~loc tag_name args children =
let analysis =
Static_analysis.analyze_element ~tag_name ~attrs:args ~children
in
match analysis with
| Static_analysis.Fully_static html ->
let html_with_doctype = Static_analysis.maybe_add_doctype tag_name html in
let html_expr = estring ~loc html_with_doctype in
[%expr JSX.unsafe [%e html_expr]]
| Static_analysis.Needs_string_concat parts
| Static_analysis.Needs_buffer parts ->
generate_buffer_code ~loc parts
| Static_analysis.Needs_conditional _ | Static_analysis.Cannot_optimize ->
rewrite_node_unoptimized ~loc tag_name args children
let rewrite_node ~loc tag_name args children =
if !disable_static_optimization then
rewrite_node_unoptimized ~loc tag_name args children
else rewrite_node_optimized ~loc tag_name args children
let split_args ~mapper args =
let children = ref (Location.none, []) in
let rest =
List.filter_map args ~f:(function
| Labelled "children", children_expression ->
let children' =
unwrap_children []
~f:(fun e ->
let expression =
match e.pexp_desc with
| Pexp_constant (Pconst_string _) ->
let loc = e.pexp_loc in
[%expr JSX.string [%e e]]
| _ -> e
in
mapper expression)
children_expression
in
children := (children_expression.pexp_loc, children');
None
| arg_label, expression -> Some (arg_label, mapper expression))
in
let children_prop =
match !children with _, [] -> None | _loc, children -> Some children
in
(children_prop, rest)
let reverse_pexp_list ~loc expr =
let rec go acc = function
| [%expr []] -> acc
| [%expr [%e? hd] :: [%e? tl]] -> go [%expr [%e hd] :: [%e acc]] tl
| expr -> expr
in
go [%expr []] expr
let list_have_tail expr =
match expr with
| Pexp_construct
({ txt = Lident "::"; _ }, Some { pexp_desc = Pexp_tuple _; _ })
| Pexp_construct ({ txt = Lident "[]"; _ }, None) ->
false
| _ -> true
let transform_items_of_list ~loc ~mapper children =
let rec run_mapper children accum =
match children with
| [%expr []] -> reverse_pexp_list ~loc accum
| [%expr [%e? v] :: [%e? acc]] when list_have_tail acc.pexp_desc ->
[%expr [%e mapper#expression v]]
| [%expr [%e? v] :: [%e? acc]] ->
run_mapper acc [%expr [%e mapper#expression v] :: [%e accum]]
| notAList -> mapper#expression notAList
in
run_mapper children [%expr []]
let rewrite_jsx =
object (self)
inherit Ast_traverse.map as super
method! expression expr =
try
match expr.pexp_desc with
| Pexp_apply (({ pexp_desc = Pexp_ident _; _ } as tag), args)
when has_jsx_attr expr.pexp_attributes -> (
let children, rest_of_args =
split_args ~mapper:self#expression args
in
match tag.pexp_desc with
| Pexp_ident { txt = Lident name; loc = name_loc }
when Html.is_html_element name || Html.is_svg_element name ->
rewrite_node ~loc:name_loc name rest_of_args children
| Pexp_ident
{ txt = Ldot (modulePath, ("createElement" | "make")); loc } ->
let id = { loc; txt = Ldot (modulePath, "make") } in
rewrite_component ~loc:tag.pexp_loc id rest_of_args children
| Pexp_ident id ->
rewrite_component ~loc:tag.pexp_loc id rest_of_args children
| _ -> assert false)
| Pexp_apply (_tag, _props) when has_jsx_attr expr.pexp_attributes ->
raise_errorf ~loc:expr.pexp_loc "tag should be an identifier"
| Pexp_construct
({ txt = Lident "::"; loc }, Some { pexp_desc = Pexp_tuple _; _ })
| Pexp_construct ({ txt = Lident "[]"; loc }, None) -> (
let jsx_attr, rest_attributes =
List.partition ~f:is_jsx expr.pexp_attributes
in
match (jsx_attr, rest_attributes) with
| [], _ -> super#expression expr
| _, _rest_attributes ->
let children = transform_items_of_list ~loc ~mapper:self expr in
[%expr JSX.list [%e children]])
| _ -> super#expression expr
with Error err -> [%expr [%e err]]
end
let () =
let driver_args =
[
( "Enable htmx attributes in HTML and SVG elements",
"-htmx",
Arg.Unit (fun () -> Extra_attributes.set Htmx) );
( "Enable react attributes in HTML and SVG elements",
"-react",
Arg.Unit (fun () -> Extra_attributes.set React) );
( "Disable static HTML optimization (use JSX.node for all elements)",
"-disable-static-opt",
Arg.Unit (fun () -> disable_static_optimization := true) );
]
in
List.iter
~f:(fun (doc, key, spec) -> Driver.add_arg key spec ~doc)
driver_args;
Driver.register_transformation "html_of_jsx.ppx"
~preprocess_impl:rewrite_jsx#structure