Source file Style_rewrite.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
(* Rewrites [ReactDOM.Style.make ~foo:a ~bar:b ()] at compile time into a
   direct list of [(kebab, camel, value)] tuples, avoiding the 347-optional-arg
   calling convention overhead (~1460 words/call on stock OCaml).

   The PPX only rewrites calls where:
   - the function is literally [ReactDOM.Style.make] (or [Style.make] in the
     ReactDOM module namespace), and
   - all arguments are labelled (not optional), and
   - the final arg is [()].
   Calls that don't fit fall through to the runtime function. *)

open Ppxlib
open Ast_builder.Default

(* CamelCase -> kebab-case mapping, kept in sync with ReactDOMStyle.ml. *)
let mapping =
  [
    ("azimuth", "azimuth");
    ("background", "background");
    ("backgroundAttachment", "background-attachment");
    ("backgroundColor", "background-color");
    ("backgroundImage", "background-image");
    ("backgroundPosition", "background-position");
    ("backgroundRepeat", "background-repeat");
    ("border", "border");
    ("borderCollapse", "border-collapse");
    ("borderColor", "border-color");
    ("borderSpacing", "border-spacing");
    ("borderStyle", "border-style");
    ("borderTop", "border-top");
    ("borderRight", "border-right");
    ("borderBottom", "border-bottom");
    ("borderLeft", "border-left");
    ("borderTopColor", "border-top-color");
    ("borderRightColor", "border-right-color");
    ("borderBottomColor", "border-bottom-color");
    ("borderLeftColor", "border-left-color");
    ("borderTopStyle", "border-top-style");
    ("borderRightStyle", "border-right-style");
    ("borderBottomStyle", "border-bottom-style");
    ("borderLeftStyle", "border-left-style");
    ("borderTopWidth", "border-top-width");
    ("borderRightWidth", "border-right-width");
    ("borderBottomWidth", "border-bottom-width");
    ("borderLeftWidth", "border-left-width");
    ("borderWidth", "border-width");
    ("bottom", "bottom");
    ("captionSide", "caption-side");
    ("clear", "clear");
    ("color", "color");
    ("content", "content");
    ("counterIncrement", "counter-increment");
    ("counterReset", "counter-reset");
    ("cue", "cue");
    ("cueAfter", "cue-after");
    ("cueBefore", "cue-before");
    ("cursor", "cursor");
    ("direction", "direction");
    ("display", "display");
    ("elevation", "elevation");
    ("emptyCells", "empty-cells");
    ("float", "float");
    ("font", "font");
    ("fontFamily", "font-family");
    ("fontSize", "font-size");
    ("fontSizeAdjust", "font-size-adjust");
    ("fontStretch", "font-stretch");
    ("fontStyle", "font-style");
    ("fontVariant", "font-variant");
    ("fontWeight", "font-weight");
    ("height", "height");
    ("left", "left");
    ("letterSpacing", "letter-spacing");
    ("lineHeight", "line-height");
    ("listStyle", "list-style");
    ("listStyleImage", "list-style-image");
    ("listStylePosition", "list-style-position");
    ("listStyleType", "list-style-type");
    ("margin", "margin");
    ("marginTop", "margin-top");
    ("marginRight", "margin-right");
    ("marginBottom", "margin-bottom");
    ("marginLeft", "margin-left");
    ("markerOffset", "marker-offset");
    ("marks", "marks");
    ("maxHeight", "max-height");
    ("maxWidth", "max-width");
    ("minHeight", "min-height");
    ("minWidth", "min-width");
    ("orphans", "orphans");
    ("outline", "outline");
    ("outlineColor", "outline-color");
    ("outlineStyle", "outline-style");
    ("outlineWidth", "outline-width");
    ("overflow", "overflow");
    ("overflowX", "overflow-x");
    ("overflowY", "overflow-y");
    ("padding", "padding");
    ("paddingTop", "padding-top");
    ("paddingRight", "padding-right");
    ("paddingBottom", "padding-bottom");
    ("paddingLeft", "padding-left");
    ("page", "page");
    ("pageBreakAfter", "page-break-after");
    ("pageBreakBefore", "page-break-before");
    ("pageBreakInside", "page-break-inside");
    ("pause", "pause");
    ("pauseAfter", "pause-after");
    ("pauseBefore", "pause-before");
    ("pitch", "pitch");
    ("pitchRange", "pitch-range");
    ("playDuring", "play-during");
    ("position", "position");
    ("quotes", "quotes");
    ("richness", "richness");
    ("right", "right");
    ("size", "size");
    ("speak", "speak");
    ("speakHeader", "speak-header");
    ("speakNumeral", "speak-numeral");
    ("speakPunctuation", "speak-punctuation");
    ("speechRate", "speech-rate");
    ("stress", "stress");
    ("tableLayout", "table-layout");
    ("textAlign", "text-align");
    ("textDecoration", "text-decoration");
    ("textIndent", "text-indent");
    ("textShadow", "text-shadow");
    ("textTransform", "text-transform");
    ("top", "top");
    ("unicodeBidi", "unicode-bidi");
    ("verticalAlign", "vertical-align");
    ("visibility", "visibility");
    ("voiceFamily", "voice-family");
    ("volume", "volume");
    ("whiteSpace", "white-space");
    ("widows", "widows");
    ("width", "width");
    ("wordSpacing", "word-spacing");
    ("zIndex", "z-index");
    ("opacity", "opacity");
    ("backgroundOrigin", "background-origin");
    ("backgroundSize", "background-size");
    ("backgroundClip", "background-clip");
    ("borderRadius", "border-radius");
    ("borderTopLeftRadius", "border-top-left-radius");
    ("borderTopRightRadius", "border-top-right-radius");
    ("borderBottomLeftRadius", "border-bottom-left-radius");
    ("borderBottomRightRadius", "border-bottom-right-radius");
    ("borderImage", "border-image");
    ("borderImageSource", "border-image-source");
    ("borderImageSlice", "border-image-slice");
    ("borderImageWidth", "border-image-width");
    ("borderImageOutset", "border-image-outset");
    ("borderImageRepeat", "border-image-repeat");
    ("boxShadow", "box-shadow");
    ("columns", "columns");
    ("columnCount", "column-count");
    ("columnFill", "column-fill");
    ("columnGap", "column-gap");
    ("columnRule", "column-rule");
    ("columnRuleColor", "column-rule-color");
    ("columnRuleStyle", "column-rule-style");
    ("columnRuleWidth", "column-rule-width");
    ("columnSpan", "column-span");
    ("columnWidth", "column-width");
    ("breakAfter", "break-after");
    ("breakBefore", "break-before");
    ("breakInside", "break-inside");
    ("rest", "rest");
    ("restAfter", "rest-after");
    ("restBefore", "rest-before");
    ("speakAs", "speak-as");
    ("voiceBalance", "voice-balance");
    ("voiceDuration", "voice-duration");
    ("voicePitch", "voice-pitch");
    ("voiceRange", "voice-range");
    ("voiceRate", "voice-rate");
    ("voiceStress", "voice-stress");
    ("voiceVolume", "voice-volume");
    ("objectFit", "object-fit");
    ("objectPosition", "object-position");
    ("imageResolution", "image-resolution");
    ("imageOrientation", "image-orientation");
    ("alignContent", "align-content");
    ("alignItems", "align-items");
    ("alignSelf", "align-self");
    ("flex", "flex");
    ("flexBasis", "flex-basis");
    ("flexDirection", "flex-direction");
    ("flexFlow", "flex-flow");
    ("flexGrow", "flex-grow");
    ("flexShrink", "flex-shrink");
    ("flexWrap", "flex-wrap");
    ("justifyContent", "justify-content");
    ("order", "order");
    ("textDecorationColor", "text-decoration-color");
    ("textDecorationLine", "text-decoration-line");
    ("textDecorationSkip", "text-decoration-skip");
    ("textDecorationStyle", "text-decoration-style");
    ("textEmphasis", "text-emphasis");
    ("textEmphasisColor", "text-emphasis-color");
    ("textEmphasisPosition", "text-emphasis-position");
    ("textEmphasisStyle", "text-emphasis-style");
    ("textUnderlinePosition", "text-underline-position");
    ("fontFeatureSettings", "font-feature-settings");
    ("fontKerning", "font-kerning");
    ("fontLanguageOverride", "font-language-override");
    ("fontSynthesis", "font-synthesis");
    ("forntVariantAlternates", "fornt-variant-alternates");
    ("fontVariantCaps", "font-variant-caps");
    ("fontVariantEastAsian", "font-variant-east-asian");
    ("fontVariantLigatures", "font-variant-ligatures");
    ("fontVariantNumeric", "font-variant-numeric");
    ("fontVariantPosition", "font-variant-position");
    ("all", "all");
    ("textCombineUpright", "text-combine-upright");
    ("textOrientation", "text-orientation");
    ("writingMode", "writing-mode");
    ("shapeImageThreshold", "shape-image-threshold");
    ("shapeMargin", "shape-margin");
    ("shapeOutside", "shape-outside");
    ("mask", "mask");
    ("maskBorder", "mask-border");
    ("maskBorderMode", "mask-border-mode");
    ("maskBorderOutset", "mask-border-outset");
    ("maskBorderRepeat", "mask-border-repeat");
    ("maskBorderSlice", "mask-border-slice");
    ("maskBorderSource", "mask-border-source");
    ("maskBorderWidth", "mask-border-width");
    ("maskClip", "mask-clip");
    ("maskComposite", "mask-composite");
    ("maskImage", "mask-image");
    ("maskMode", "mask-mode");
    ("maskOrigin", "mask-origin");
    ("maskPosition", "mask-position");
    ("maskRepeat", "mask-repeat");
    ("maskSize", "mask-size");
    ("maskType", "mask-type");
    ("backgroundBlendMode", "background-blend-mode");
    ("isolation", "isolation");
    ("mixBlendMode", "mix-blend-mode");
    ("boxDecorationBreak", "box-decoration-break");
    ("boxSizing", "box-sizing");
    ("caretColor", "caret-color");
    ("navDown", "nav-down");
    ("navLeft", "nav-left");
    ("navRight", "nav-right");
    ("navUp", "nav-up");
    ("outlineOffset", "outline-offset");
    ("resize", "resize");
    ("textOverflow", "text-overflow");
    ("grid", "grid");
    ("gridArea", "grid-area");
    ("gridAutoColumns", "grid-auto-columns");
    ("gridAutoFlow", "grid-auto-flow");
    ("gridAutoRows", "grid-auto-rows");
    ("gridColumn", "grid-column");
    ("gridColumnEnd", "grid-column-end");
    ("gridColumnGap", "grid-column-gap");
    ("gridColumnStart", "grid-column-start");
    ("gridGap", "grid-gap");
    ("gridRow", "grid-row");
    ("gridRowEnd", "grid-row-end");
    ("gridRowGap", "grid-row-gap");
    ("gridRowStart", "grid-row-start");
    ("gridTemplate", "grid-template");
    ("gridTemplateAreas", "grid-template-areas");
    ("gridTemplateColumns", "grid-template-columns");
    ("gridTemplateRows", "grid-template-rows");
    ("willChange", "will-change");
    ("hangingPunctuation", "hanging-punctuation");
    ("hyphens", "hyphens");
    ("lineBreak", "line-break");
    ("overflowWrap", "overflow-wrap");
    ("tabSize", "tab-size");
    ("textAlignLast", "text-align-last");
    ("textJustify", "text-justify");
    ("wordBreak", "word-break");
    ("wordWrap", "word-wrap");
    ("animation", "animation");
    ("animationDelay", "animation-delay");
    ("animationDirection", "animation-direction");
    ("animationDuration", "animation-duration");
    ("animationFillMode", "animation-fill-mode");
    ("animationIterationCount", "animation-iteration-count");
    ("animationName", "animation-name");
    ("animationPlayState", "animation-play-state");
    ("animationTimingFunction", "animation-timing-function");
    ("transition", "transition");
    ("transitionDelay", "transition-delay");
    ("transitionDuration", "transition-duration");
    ("transitionProperty", "transition-property");
    ("transitionTimingFunction", "transition-timing-function");
    ("backfaceVisibility", "backface-visibility");
    ("perspective", "perspective");
    ("perspectiveOrigin", "perspective-origin");
    ("transform", "transform");
    ("transformOrigin", "transform-origin");
    ("transformStyle", "transform-style");
    ("justifyItems", "justify-items");
    ("justifySelf", "justify-self");
    ("placeContent", "place-content");
    ("placeItems", "place-items");
    ("placeSelf", "place-self");
    ("appearance", "appearance");
    ("caret", "caret");
    ("caretAnimation", "caret-animation");
    ("caretShape", "caret-shape");
    ("userSelect", "user-select");
    ("maxLines", "max-lines");
    ("marqueeDirection", "marquee-direction");
    ("marqueeLoop", "marquee-loop");
    ("marqueeSpeed", "marquee-speed");
    ("marqueeStyle", "marquee-style");
    ("overflowStyle", "overflow-style");
    ("rotation", "rotation");
    ("rotationPoint", "rotation-point");
    ("alignmentBaseline", "alignment-baseline");
    ("baselineShift", "baseline-shift");
    ("clip", "clip");
    ("clipPath", "clip-path");
    ("clipRule", "clip-rule");
    ("colorInterpolation", "color-interpolation");
    ("colorInterpolationFilters", "color-interpolation-filters");
    ("colorProfile", "color-profile");
    ("colorRendering", "color-rendering");
    ("dominantBaseline", "dominant-baseline");
    ("fill", "fill");
    ("fillOpacity", "fill-opacity");
    ("fillRule", "fill-rule");
    ("filter", "filter");
    ("floodColor", "flood-color");
    ("floodOpacity", "flood-opacity");
    ("glyphOrientationHorizontal", "glyph-orientation-horizontal");
    ("glyphOrientationVertical", "glyph-orientation-vertical");
    ("imageRendering", "image-rendering");
    ("kerning", "kerning");
    ("lightingColor", "lighting-color");
    ("markerEnd", "marker-end");
    ("markerMid", "marker-mid");
    ("markerStart", "marker-start");
    ("pointerEvents", "pointer-events");
    ("shapeRendering", "shape-rendering");
    ("stopColor", "stop-color");
    ("stopOpacity", "stop-opacity");
    ("stroke", "stroke");
    ("strokeDasharray", "stroke-dasharray");
    ("strokeDashoffset", "stroke-dashoffset");
    ("strokeLinecap", "stroke-linecap");
    ("strokeLinejoin", "stroke-linejoin");
    ("strokeMiterlimit", "stroke-miterlimit");
    ("strokeOpacity", "stroke-opacity");
    ("strokeWidth", "stroke-width");
    ("textAnchor", "text-anchor");
    ("textRendering", "text-rendering");
    ("rubyAlign", "ruby-align");
    ("rubyMerge", "ruby-merge");
    ("rubyPosition", "ruby-position");
  ]

(* Assoc of camel -> (kebab, signature_index). *)
let indexed_mapping = List.mapi (fun i (camel, kebab) -> (camel, (kebab, i))) mapping
let find_camel camel = List.assoc_opt camel indexed_mapping

(* Returns true if [longident] is [ReactDOM.Style.make] (possibly prefixed). *)
let is_style_make_ident = function
  | Ldot (Ldot (Lident "ReactDOM", "Style"), "make") -> true
  | Ldot (Lident "Style", "make") -> true (* used inside ReactDOM module *)
  | _ -> false

(* Attempt to rewrite a call [ReactDOM.Style.make ~foo:a ~bar:b ()] to a direct
   list expression. Returns [Some new_expr] on success, [None] otherwise.

   The final arg must be [()] (Nolabel, unit), and there must be no optional
   args and no unknown label names.

   The output list must match the runtime order produced by [Style.make]:
   signature order (the body prepends in signature order and reverses at the
   end). Signature order is also the JS object key order melange produces for
   reason-react's [ReactDOM.Style.make], which react-dom preserves in both
   inline style output and the Flight payload. *)
let try_rewrite_call ~loc:_ args =
  let rec collect acc = function
    | [] -> None (* missing the final unit *)
    | [ (Nolabel, { pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, None); _ }) ] -> Some acc
    | (Labelled name, expr) :: rest -> (
        match find_camel name with
        | Some (kebab, idx) -> collect ((idx, name, kebab, expr) :: acc) rest
        | None ->
            (* unknown style name — fall back *)
            None)
    | (Optional _, _) :: _ -> None (* optional arg — fall back *)
    | (Nolabel, _) :: _ -> None (* unexpected positional — fall back *)
  in
  match collect [] args with
  | None -> None
  | Some entries ->
      (* Sort by signature index ascending, matching the runtime [make]'s
         output order. *)
      let sorted = List.sort (fun (i, _, _, _) (j, _, _, _) -> Int.compare i j) entries in
      let loc = Location.none in
      let list_expr =
        List.fold_right
          (fun (_, camel, kebab, expr) acc ->
            let loc = expr.pexp_loc in
            [%expr ([%e estring ~loc kebab], [%e estring ~loc camel], [%e expr]) :: [%e acc]])
          sorted
          [%expr ([] : (string * string * string) list)]
      in
      Some [%expr ([%e list_expr] : ReactDOM.Style.t)]

(* Top-level rewriter: looks at any [Pexp_apply] and rewrites eligible ones. *)
let rewrite_expression expr =
  match expr.pexp_desc with
  | Pexp_apply ({ pexp_desc = Pexp_ident { txt; _ }; _ }, args) when is_style_make_ident txt -> (
      match try_rewrite_call ~loc:expr.pexp_loc args with Some new_expr -> new_expr | None -> expr)
  | _ -> expr