Source file optimize.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
(** CSS optimization implementation *)

open Declaration
open Stylesheet
open Common
module String_set = Set.Make (String)

let src = Logs.Src.create "cascade.optimize" ~doc:"Cascade CSS optimizer"

module Log = (val Logs.src_log src : Logs.LOG)

(** {1 Configuration} *)

type scope = Ctx.scope
type objective = [ `Raw | `Transfer ]
type browser_version = int * int

type targets = Support.targets = {
  chrome : browser_version;
  firefox : browser_version;
  safari : browser_version;
  ios_safari : browser_version;
}

let evergreen_targets = Support.evergreen

(* Optimisation context threaded from the entry points to the shorthand
   composers. [scope] drives fragment-vs-stylesheet decisions; [registered]
   reports whether a custom property has an [@property] initial-value, so
   folding its [var()] into a shorthand cannot widen an
   invalid-at-computed-value failure. Default: fragment, nothing registered. *)
type ctx = Ctx.t

let ctx_of_scope = Ctx.of_scope

let option_map_preserve (f : 'a -> 'a) (value : 'a option) : 'a option =
  match value with
  | None -> (None : 'a option)
  | Some x ->
      let y = f x in
      if y == x then value else Some y

let rule_with_nested (rule : rule) nested =
  if nested == rule.nested then rule else { rule with nested }

(** {1 Declaration Optimization} *)

let merge_overflow_longhands = Shorthand.merge_overflow_longhands
let merge_box_shorthand_longhands = Shorthand.merge_box_shorthand_longhands
let compose_shorthands = Shorthand.compose_shorthands
let deduplicate_declarations = Shorthand.deduplicate_declarations

(** {1 Statement Optimization} *)

let merge_consecutive_layers = Block.merge_consecutive_layers
let merge_consecutive_media = Block.merge_consecutive_media
let merge_distant_media = Block.merge_distant_media
let merge_consecutive_supports = Block.merge_consecutive_supports
let merge_consecutive_containers = Block.merge_consecutive_containers
let merge_distant_containers = Block.merge_distant_containers
let merge_distant_supports = Block.merge_distant_supports
let merge_consecutive_starting_style = Block.merge_consecutive_starting_style
let drop_empty_rules = Block.drop_empty_rules
let merge_named_layers_by_name = Block.merge_named_layers_by_name

(* A guard the enclosing context leaves open is put to the browsers the run
   judges for, when it judges for any, each target standing for its release and
   every later one: one all of them satisfy asks a question they all answer yes
   to, and one all of them fail selects none of them. Otherwise the guard stays
   for the engine to answer. *)
let supports_decision ~ctx ~supports cond =
  match Supports.simplify_under ~context:supports cond with
  | `Cond cond' as open_guard -> (
      match Ctx.judge ctx with
      | Some targets -> (
          match Supports.implemented_by targets cond' with
          | Some true -> `True
          | Some false -> `False
          | None -> open_guard)
      | None -> open_guard)
  | decided -> decided

(* The run of [Rule]s a statement list opens with, as statements and as rules,
   with what follows it. An [@supports] the context already answers holds
   wherever the enclosing block does, so its contents apply exactly where they
   sit: the guard is dropped and its block joins the stream, and a rule it opens
   with continues the run. Splicing here, while the run is collected, costs the
   guard nothing; unwrapping it after the run was processed would send the
   preceding rules through the local passes once per guard. *)
(* CSS Cascade 5 sec. 7.3.6 rolls a [revert-rule] value back past the style rule
   holding it, so that rule is a run of its own: the run passes merge, factor
   and shadow across rules, and each would change what the keyword rolls back
   to. *)
let rolls_back (r : rule) =
  List.exists Declaration.rolls_back_rule r.declarations

(* [rules] cut so that each rule {!rolls_back} stands alone. *)
let split_rollbacks rules =
  let flush runs = function [] -> runs | run -> List.rev run :: runs in
  let rec go runs run = function
    | [] -> List.rev (flush runs run)
    | r :: rest when rolls_back r -> go ([ r ] :: flush runs run) [] rest
    | r :: rest -> go runs (r :: run) rest
  in
  go [] [] rules

let rec collect_rules ~holds (stmt_acc : statement list) (rules_acc : rule list)
    : statement list -> statement list * rule list * statement list = function
  | (Rule r as stmt) :: rest when not (rolls_back r) ->
      collect_rules ~holds (stmt :: stmt_acc) (r :: rules_acc) rest
  | Supports (cond, block) :: rest when holds cond ->
      collect_rules ~holds stmt_acc rules_acc (block @ rest)
  | rest -> (List.rev stmt_acc, List.rev rules_acc, rest)

let factor_rules_incremental ?cache ~settle ~ctx ~held rules =
  Factor.run ?cache ~settle ~ctx ~finalize:(Rule.finalize ~held ~ctx) rules

let merge_adjacent_and_mark ~ctx merged rules =
  let settled = Rule.merge_adjacent_identical ~ctx rules in
  (* Each produced rule is fully normalized by the scheduler's finalizer. A node
     merge is therefore the only settling step that changes the candidate graph
     and requires another global walk. *)
  if settled != rules then merged := true;
  settled

(* A merge of adjacent rules that settling makes is a new graph, so the run is
   factored again until settling merges nothing. Every merge drops a rule, so
   the loop ends. *)
let rec factor_rules_until_settled ?factor_cache ~ctx ~held rules =
  let merged = ref false in
  let next =
    factor_rules_incremental ?cache:factor_cache
      ~settle:(merge_adjacent_and_mark ~ctx merged)
      ~ctx ~held rules
  in
  if !merged then factor_rules_until_settled ?factor_cache ~ctx ~held next
  else next

(* [@scope] bounds are parsed selectors; canonicalize them like any other
   selector so a list bound is de-duplicated and ordered consistently. *)
let canonicalize_scope_selector ~enforce_spec sel =
  Selector.canonicalize ~enforce_spec sel

(* CSS Fonts 4 (ED) sec. 4.4 gives the [font-weight] and [font-width]
   descriptors the values of the properties of the same name, so a descriptor
   takes its property's fold. A descriptor is not a declaration and never
   reaches factoring, but the fold is still a node question, so it belongs here
   and not in the serializer. *)
let normalize_font_face_descriptor (desc : font_face_descriptor) :
    font_face_descriptor =
  let weight w = Properties.normalize_property_value Properties.Font_weight w in
  let stretch w =
    Properties.normalize_property_value Properties.Font_stretch w
  in
  match desc with
  | Font_weight value ->
      let value' = weight value in
      if value' == value then desc else Font_weight value'
  | Font_weight_range (low, high) ->
      let low' = weight low in
      let high' = weight high in
      if low' == low && high' == high then desc
      else Font_weight_range (low', high')
  | Font_stretch value ->
      let value' = stretch value in
      if value' == value then desc else Font_stretch value'
  | Font_stretch_range (low, high) ->
      let low' = stretch low in
      let high' = stretch high in
      if low' == low && high' == high then desc
      else Font_stretch_range (low', high')
  | Font_family _ | Font_family_as_written _ | Src _ | Font_style _
  | Font_display _ | Unicode_range _ | Font_variant _ | Font_feature_settings _
  | Font_variation_settings _ | Font_variation_settings_as_written _
  | Size_adjust _ | Ascent_override _ | Descent_override _ | Line_gap_override _
  | Font_style_auto | Font_weight_auto | Font_stretch_auto ->
      desc

(* [stmt] is returned unchanged when no descriptor moved: the factoring fixpoint
   reads a no-op off physical identity. *)
let normalize_font_face stmt descriptors =
  let descriptors' =
    List.map_preserve normalize_font_face_descriptor descriptors
  in
  if descriptors' == descriptors then stmt else Font_face descriptors'

(* Nested rule selectors are implicitly relative to the parent [&], so drop a
   redundant leading [& <combinator>] (CSS Nesting 1 sec. 3), where every target
   parses the relaxed form: Chrome 112 to 119 and Safari 16.5 to 17.1 refuse a
   nested selector that starts with an identifier. *)
let drop_nesting_prefix (stmt : statement) : statement =
  match stmt with
  | Rule nr ->
      let selector = Selector.drop_redundant_nesting_prefix nr.selector in
      if selector == nr.selector then stmt else Rule { nr with selector }
  | other -> other

(* CSS Cascade 6 sec. 2.5.2: an [@scope] body's rules and declarations stand for
   the scoping root, which [&] names there, not for the enclosing rule. *)
let scope_owner =
  Some
    {
      selector = Selector.Nesting;
      declarations = [];
      nested = [];
      merge_key = None;
    }

(* The blocks of [stmts] a rule dropped from left empty, at any depth: the pass
   that optimized them dropped the empty blocks it saw before the rule went. *)
let rec drop_emptied_blocks stmts =
  drop_empty_rules
    (List.map_preserve (map_statement_children drop_emptied_blocks) stmts)

let rec statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (stmts : statement list) : statement list =
  match stmts with
  | [] -> stmts
  | _ ->
      (* [Block.drop_misplaced_prelude] runs first: an [@import] after a style
         rule is invalid and ignored by browsers (CSS Cascade 5 sec. 2), so it
         must not act as a cascade boundary. Stripping it up front lets the
         rules it falsely separated merge in this same pass, keeping
         [statements] idempotent (stripping after the merge would leave a re-run
         to combine them). *)
      let stmts' =
        let stmts =
          Block.drop_misplaced_prelude stmts |> merge_named_layers_by_name
        in
        let stmts =
          process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
            [] stmts
        in
        let stmts =
          if Ctx.regroup ctx then
            nest ?factor_cache ~ctx ~enforce_spec ~owner ~supports stmts
          else stmts
        in
        let stmts =
          let merged =
            merge_blocks ?factor_cache ~ctx ~enforce_spec ~owner ~supports stmts
          in
          if merged == stmts then stmts
          else
            rejoin_runs ?factor_cache ~ctx ~enforce_spec ~owner ~supports
              ~before:stmts merged
        in
        stmts |> Block.merge_layer_declarations |> drop_empty_rules
      in
      List.preserve stmts stmts'

(* Join the conditional and [@starting-style] blocks of [stmts] the cascade lets
   join. A merge concatenates blocks whose children are already optimized, so
   only that new seam is optimized again: descending again walks a nested child
   once per ancestor and turns linear depth into quadratic work. Further merges
   in the seam pass stay shallow too. *)
and merge_blocks ?factor_cache ~ctx ~enforce_spec ~owner ~supports stmts =
  let optimize_merged_block =
    statements ?factor_cache
      ~ctx:(Ctx.with_recurse_blocks false ctx)
      ~enforce_spec ~owner ~supports
  in
  stmts
  |> merge_consecutive_media ~optimize_merged_block
  |> merge_distant_media ?owner ~optimize_merged_block
  |> merge_consecutive_supports ~optimize_merged_block
  |> merge_distant_supports ?owner ~optimize_merged_block
  |> merge_consecutive_containers ~optimize_merged_block
  |> merge_distant_containers ?owner ~optimize_merged_block
  |> merge_consecutive_starting_style ~optimize_merged_block

(* A block a merge took away can leave two rule runs of [merged] adjacent, and
   the run they make was optimized as two. [before] is the list the merge read:
   it holds every rule statement [merged] does, in the same order, so a run is
   joined where two of its rules sit apart there. Each joined run is optimized
   again as the one run it now is, its rules' bodies aside, which are already,
   and the regrouping reads the list again when one changed. *)
and rejoin_runs ?factor_cache ~ctx ~enforce_spec ~owner ~supports ~before merged
    =
  let shallow = Ctx.with_recurse_blocks false ctx in
  let changed = ref false in
  let flush acc run joined =
    let stmts = List.rev_map fst run in
    if not joined then List.rev_append stmts acc
    else
      let rules = List.rev_map snd run in
      let rules' =
        rules_aux ?factor_cache ~ctx:shallow ~enforce_spec ~owner ~supports
          rules
      in
      if rules' == rules then List.rev_append stmts acc
      else begin
        changed := true;
        List.rev_append (List.map (fun r -> Rule r) rules') acc
      end
  in
  (* Whether a statement of [before] comes before [stmt], and what follows. *)
  let rec find stmt skipped = function
    | s :: rest when s == stmt -> (skipped, rest)
    | _ :: rest -> find stmt true rest
    | [] -> (true, [])
  in
  let rec walk acc run joined before = function
    | [] -> List.rev (flush acc run joined)
    | (Rule r as stmt) :: rest when not (rolls_back r) ->
        let skipped, before = find stmt false before in
        let joined =
          joined || match run with [] -> false | _ :: _ -> skipped
        in
        walk acc ((stmt, r) :: run) joined before rest
    | stmt :: rest -> walk (stmt :: flush acc run joined) [] false before rest
  in
  let rejoined = walk [] [] false before merged in
  if not !changed then merged
  else if Ctx.regroup ctx then
    nest ?factor_cache ~ctx ~enforce_spec ~owner ~supports rejoined
  else rejoined

(* Nesting takes a flat rule into the rule before it, which changes the run both
   were optimized in: the rule taken is gone, and its parent, which now nests a
   rule, is no member of the run's factoring buckets. Each run nesting changed
   is optimized again as the run it now is, its rules' bodies aside, which are
   already, and nested again. Nesting and factoring each shorten the run, so
   this ends. *)
and nest ?factor_cache ~ctx ~enforce_spec ~owner ~supports stmts =
  let nested =
    if Ctx.parses_nesting ctx then Nest.statements stmts else stmts
  in
  if nested == stmts then stmts
  else
    let shallow = Ctx.with_recurse_blocks false ctx in
    let changed = ref false in
    (* The rule runs of [stmts] and [nested] pair up in order: nesting changes
       no other statement and leaves every run at least its first rule. *)
    let rec runs acc run = function
      | (Rule r as stmt) :: rest -> runs acc ((stmt, r) :: run) rest
      | rest -> (
          let acc = match run with [] -> acc | _ -> List.rev run :: acc in
          match rest with [] -> List.rev acc | _ :: rest -> runs acc [] rest)
    in
    let before = runs [] [] stmts in
    let rec walk acc before = function
      | [] -> List.rev acc
      | Rule _ :: _ as stmts -> (
          let rec take run = function
            | (Rule r as stmt) :: rest -> take ((stmt, r) :: run) rest
            | rest -> (List.rev run, rest)
          in
          let run, rest = take [] stmts in
          match before with
          | old :: before ->
              let same = List.equal (fun (a, _) (b, _) -> a == b) old run in
              let acc =
                if same then List.rev_append (List.map fst run) acc
                else
                  let rules = List.map snd run in
                  let rules' =
                    rules_aux ?factor_cache ~ctx:shallow ~enforce_spec ~owner
                      ~supports rules
                  in
                  if rules' == rules then List.rev_append (List.map fst run) acc
                  else begin
                    changed := true;
                    List.rev_append (List.map (fun r -> Rule r) rules') acc
                  end
              in
              walk acc before rest
          | [] -> walk (List.rev_append (List.map fst run) acc) [] rest)
      | stmt :: rest -> walk (stmt :: acc) before rest
    in
    let optimized = walk [] before nested in
    if !changed then
      nest ?factor_cache ~ctx ~enforce_spec ~owner ~supports optimized
    else nested

(* Walk the statement list left to right over a reversed accumulator.

   CSS Counter Styles 3 sec. 3: a [@counter-style] with no descriptor defines no
   counter style, and a name that defines none falls back to [decimal] exactly
   as an unknown name does, so the rule renders nothing and goes. *)
and process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (acc : statement list) (remaining : statement list) : statement list =
  match remaining with
  | [] -> List.rev acc
  | (Rule r as stmt) :: rest ->
      process_rule_run ?factor_cache ~ctx ~enforce_spec ~owner ~supports acc
        stmt r rest
  | (Media (cond, block) as stmt) :: rest ->
      process_media_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        acc stmt cond block rest
  | (Container (name, cond, block) as stmt) :: rest ->
      process_container_statement ?factor_cache ~ctx ~enforce_spec ~owner
        ~supports acc stmt name cond block rest
  | (Supports (cond, block) as stmt) :: rest ->
      process_supports_statement ?factor_cache ~ctx ~enforce_spec ~owner
        ~supports acc stmt cond block rest
  | (Scope (start, end_, block) as stmt) :: rest ->
      process_scope_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        acc stmt start end_ block rest
  | (Origin (origin, block) as stmt) :: rest ->
      process_group_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        acc stmt block
        (fun block -> Origin (origin, block))
        rest
  (* The wrapper is opaque but its body is an ordinary block, so it optimises
     like [@media]'s: a group left out here keeps whatever the author wrote and
     [--minify] does nothing inside it. *)
  | (Moz_document (cond, block) as stmt) :: rest ->
      process_group_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        acc stmt block
        (fun block -> Moz_document (cond, block))
        rest
  | (When (cond, block) as stmt) :: rest ->
      process_group_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        acc stmt block
        (fun block -> When (cond, block))
        rest
  | (Else (cond, block) as stmt) :: rest ->
      process_group_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        acc stmt block
        (fun block -> Else (cond, block))
        rest
  | (Starting_style block as stmt) :: rest ->
      process_group_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        acc stmt block
        (fun block -> Starting_style block)
        rest
  | (Layer (name, block) as stmt) :: rest ->
      process_layer_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        acc stmt name block rest
  | (Import _ as stmt) :: rest ->
      process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        (stmt :: acc) rest
  | (Declarations decls as stmt) :: rest ->
      process_declarations_statement ?factor_cache ~ctx ~enforce_spec ~owner
        ~supports acc stmt decls rest
  | (Font_face descriptors as stmt) :: rest ->
      process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        (normalize_font_face stmt descriptors :: acc)
        rest
  (* Listed rather than closed with a wildcard: everything left holds no block,
     so a statement that grows one has to be classified above before it
     compiles. *)
  | Counter_style (_, []) :: rest ->
      process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports acc
        rest
  | (( Property _ | Bang_comment _ | Charset _ | Namespace _ | Layer_decl _
     | Supports_condition _ | Keyframes _ | Webkit_keyframes _ | Moz_keyframes _
     | Counter_style _ | Page _ | Page_with_margins _ | Font_palette_values _
     | Font_feature_values _ | View_transition _ | Position_try _ | Viewport _
     | Unknown_at_rule _ ) as hd)
    :: rest ->
      process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        (hd :: acc) rest

and process_scope_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    acc stmt start end_ block rest =
  let start' =
    option_map_preserve (canonicalize_scope_selector ~enforce_spec) start
  in
  let end_' =
    option_map_preserve (canonicalize_scope_selector ~enforce_spec) end_
  in
  let optimized_block =
    descend_block ?factor_cache ~ctx ~enforce_spec ~owner:scope_owner ~supports
      block
  in
  let optimized =
    if start' == start && end_' == end_ && optimized_block == block then stmt
    else Scope (start', end_', optimized_block)
  in
  process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (optimized :: acc) rest

and descend_block ?factor_cache ~ctx ~enforce_spec ~owner ~supports block =
  if Ctx.recurse_blocks ctx then
    statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports block
  else block

(* A run of declarations is a declaration list wherever it sits, and nothing
   comes between two writes inside one, so the same deduplication a rule body
   gets applies (CSS Cascade 5 sec. 6.4.4: the later write wins). *)
and process_declarations_statement ?factor_cache ~ctx ~enforce_spec ~owner
    ~supports acc stmt decls rest =
  let decls' = Rule.declaration_run ~ctx decls in
  let stmt = if decls' == decls then stmt else Declarations decls' in
  process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (stmt :: acc) rest

and process_group_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    acc stmt block rebuild rest =
  let optimized_block =
    descend_block ?factor_cache ~ctx ~enforce_spec ~owner ~supports block
  in
  let optimized =
    if optimized_block == block then stmt else rebuild optimized_block
  in
  process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (optimized :: acc) rest

and process_rule_run ?factor_cache ~ctx ~enforce_spec ~owner ~supports acc stmt
    r rest =
  let holds cond = supports_decision ~ctx ~supports cond = `True in
  let plain_stmts, plain_rules, rest =
    if rolls_back r then ([ stmt ], [ r ], rest)
    else collect_rules ~holds [ stmt ] [ r ] rest
  in
  let optimized =
    rules_aux ?factor_cache ~ctx ~enforce_spec ~owner ~supports plain_rules
  in
  let as_statements =
    if optimized == plain_rules then plain_stmts
    else List.map (fun r -> Rule r) optimized
  in
  process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (List.rev_append as_statements acc)
    rest

and process_media_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    acc stmt cond block rest =
  let cond = if enforce_spec then cond else Media.lower_for_minify cond in
  let optimized_block =
    descend_block ?factor_cache ~ctx ~enforce_spec ~owner ~supports block
  in
  let optimized =
    if
      (cond == match stmt with Media (c, _) -> c | _ -> assert false)
      && optimized_block == block
    then stmt
    else Media (cond, optimized_block)
  in
  process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (optimized :: acc) rest

and process_container_statement ?factor_cache ~ctx ~enforce_spec ~owner
    ~supports acc stmt name cond block rest =
  let cond =
    if enforce_spec then cond
    else option_map_preserve Container.lower_for_minify cond
  in
  let optimized_block =
    descend_block ?factor_cache ~ctx ~enforce_spec ~owner ~supports block
  in
  let optimized =
    if
      (cond == match stmt with Container (_, c, _) -> c | _ -> assert false)
      && optimized_block == block
    then stmt
    else Container (name, cond, optimized_block)
  in
  process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (optimized :: acc) rest

and process_supports_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    acc stmt cond block rest =
  match supports_decision ~ctx ~supports cond with
  (* The guard selects no user agent, so nothing in its block is ever applied
     (CSS Conditional 3 sec. 2). Its cascade layers go with it: CSS Cascade 5
     sec. 6.4.1 keeps a layer defined inside a conditional group rule out of the
     layer order unless the condition is true, and a feature query is answered
     once for the whole document rather than per element. *)
  | `False ->
      process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports acc
        rest
  (* The guard holds wherever the block enclosing it does, so its contents apply
     exactly where they already sit: they join the enclosing stream, where
     [collect_rules] has already spliced any such guard a rule run reached. *)
  | `True ->
      process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports acc
        (block @ rest)
  | `Cond cond' ->
      let block' =
        descend_block ?factor_cache ~ctx ~enforce_spec ~owner
          ~supports:(cond' :: supports) block
      in
      let optimized =
        if cond' == cond && block' == block then stmt
        else Supports (cond', block')
      in
      process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
        (optimized :: acc) rest

and process_layer_statement ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    acc stmt name block rest =
  let optimized_block =
    descend_block ?factor_cache ~ctx ~enforce_spec ~owner ~supports block
  in
  if Block.is_layer_empty optimized_block then
    match name with
    (* A style rule holds no layer-order declaration, so inside one the empty
       block keeps its block form; folding it to [Layer_decl] emits CSS every
       engine drops. *)
    | Some _ when Option.is_some owner ->
        process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
          (Layer (name, optimized_block) :: acc)
          rest
    | Some layer_name ->
        let all_names, remaining =
          Block.collect_empty_layer_names [ layer_name ] rest
        in
        process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
          (Layer_decl all_names :: acc)
          remaining
    | None ->
        process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports acc
          rest
  else
    let optimized =
      if optimized_block == block then stmt else Layer (name, optimized_block)
    in
    process_statements ?factor_cache ~ctx ~enforce_spec ~owner ~supports
      (optimized :: acc) rest

(* Optimize one rule's nested statements recursively, then drop the redundant
   nesting prefix (see [drop_nesting_prefix]) and let a run written after them
   rejoin the rule's own declarations wherever the cascade allows. The body is
   the rule's, so it optimizes with the rule as owner, under its selector
   expanded against [owner]'s: CSS Nesting 1 sec. 3 weighs [&] as the enclosing
   rule's selector, and that one may itself be nested. Dead nested rules go
   before the hoist, so a declaration behind one is no longer held back. A run
   the hoist takes out of the body can leave two blocks it separated adjacent,
   so the body's blocks are joined again once it moved one. *)
and rule_with_optimized_nested ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (rule : rule) =
  let body_owner =
    lazy
      (match owner with
      | Option.None -> rule
      | Option.Some (o : rule) ->
          { rule with selector = Nest.combine o.selector rule.selector })
  in
  let nested =
    match (Ctx.recurse_blocks ctx, rule.nested) with
    | false, nested -> nested
    | true, [] -> []
    | true, nested ->
        let nested =
          statements ?factor_cache ~ctx ~enforce_spec
            ~owner:(Option.Some (Lazy.force body_owner))
            ~supports nested
        in
        if Ctx.parses_nesting ctx then
          List.map_preserve drop_nesting_prefix nested
        else nested
  in
  let rule =
    let rule = rule_with_nested rule nested in
    let live = Nest.drop_dead_nested rule in
    if live == rule then rule
    else rule_with_nested live (drop_emptied_blocks live.nested)
  in
  let rule =
    if Ctx.parses_nested_declarations ctx then
      Nest.nesting_rules_as_declarations rule
    else rule
  in
  let rule =
    let hoisted = Nest.hoist_declaration_runs rule in
    if hoisted == rule then rule
    else
      rule_with_nested hoisted
        (merge_blocks ?factor_cache ~ctx ~enforce_spec
           ~owner:(Option.Some (Lazy.force body_owner))
           ~supports hoisted.nested)
  in
  let rule =
    let selector = Selector.canonicalize ~enforce_spec rule.selector in
    if selector == rule.selector then rule else { rule with selector }
  in
  Nest.merge_lone ~in_scope:(owner == scope_owner) rule

and rules_aux ?factor_cache ~ctx ~enforce_spec ~owner ~supports
    (rules : rule list) : rule list =
  let with_optimized_nested =
    List.map_preserve
      (rule_with_optimized_nested ?factor_cache ~ctx ~enforce_spec ~owner
         ~supports)
      rules
  in
  (* A run contracts into a shorthand only when nothing that reaches the same
     element holds a slot the run leaves out, and one rule cannot show that. The
     scheduler below reorders and merges, so the summary covers the whole run
     rather than the prefix before each rule: it stays valid wherever a rule
     lands. *)
  let held =
    List.fold_left
      (fun held (r : rule) -> Shorthand.held_add held r.declarations)
      Shorthand.held_none with_optimized_nested
  in
  let run rules =
    (* Apply local rule normalization before the DAG factor scheduler decides
       global selector/declaration grouping. *)
    let prepared = Rule.normalize ~ctx ~held rules in
    (* Factoring is greedy and global: extracting one shared declaration subset
       can leave behind leftovers that are themselves factorable. The local
       linear optimizations above always run; this incremental gate only decides
       whether the expensive global factoring fixpoint is likely to buy enough
       bytes to justify the full indexed scheduler walk. *)
    if Ctx.regroup ctx then
      (* The global scheduler reaches a fixed point for the graph it receives,
         but settling its result can merge nodes and expose a new graph. Repeat
         only when that cheap postprocessing changed the result; most sheets
         still pay for one global walk. *)
      factor_rules_until_settled ?factor_cache ~ctx ~held prepared
    else merge_adjacent_and_mark ~ctx (ref false) prepared
  in
  (* Lifting a lone nested rule into its wrapper can leave a rule holding
     [revert-rule] in the run, which is then a run of its own
     ({!rolls_back}). *)
  match split_rollbacks with_optimized_nested with
  | [ _ ] -> run with_optimized_nested
  | runs -> List.concat_map run runs

(* CSS Animations 1 sec. 3: [@keyframes name] re-declaration overrides the
   earlier definition in source order. Drop earlier same-name keyframes; the
   later one wins. Vendor-prefixed [-webkit-] / [-moz-] variants are separate
   namespaces, so they are not dedup'd against the unprefixed form. *)
let drop_shadowed_keyframes (stmts : statement list) : statement list =
  let exists_later kind name tail =
    List.exists
      (fun stmt ->
        match (kind, stmt) with
        | `Plain, Keyframes (n, _) -> n = name
        | `Webkit, Webkit_keyframes (n, _) -> n = name
        | `Moz, Moz_keyframes (n, _) -> n = name
        | _ -> false)
      tail
  in
  let rec walk acc = function
    | [] -> List.rev acc
    | (Keyframes (name, _) as kf) :: rest ->
        if exists_later `Plain name rest then walk acc rest
        else walk (kf :: acc) rest
    | (Webkit_keyframes (name, _) as kf) :: rest ->
        if exists_later `Webkit name rest then walk acc rest
        else walk (kf :: acc) rest
    | (Moz_keyframes (name, _) as kf) :: rest ->
        if exists_later `Moz name rest then walk acc rest
        else walk (kf :: acc) rest
    | stmt :: rest -> walk (stmt :: acc) rest
  in
  List.preserve stmts (walk [] stmts)

(* CSS Cascade 5 sec. 6.4.2: rules from all occurrences of a named layer
   accumulate. Merge same-name blocks at the FIRST NON-EMPTY occurrence so
   content stays where the author placed the layer's first real declaration.
   Leading empty blocks ([@layer name {}]) stay in place for the
   [empty-named-layer -> Layer_decl] normalisation in [process_statements]. *)
let statements_top_level ?factor_cache ~ctx ~enforce_spec
    (stmts : statement list) : statement list =
  let optimize_merged_block =
    statements ?factor_cache
      ~ctx:(Ctx.with_recurse_blocks false ctx)
      ~enforce_spec ~owner:None ~supports:[]
  in
  let stmts' =
    statements ?factor_cache ~ctx ~enforce_spec ~owner:None ~supports:[] stmts
    |> merge_consecutive_layers ~optimize_merged_block
    |> Block.drop_redundant_layer_decls |> drop_shadowed_keyframes
  in
  List.preserve stmts stmts'

let single_rule ?scope (rule : rule) : rule =
  let ctx = ctx_of_scope scope in
  let rule =
    Nest.hoist_declaration_runs
      {
        rule with
        nested =
          statements ~ctx ~enforce_spec:false ~owner:(Some rule) ~supports:[]
            rule.nested;
      }
  in
  {
    rule with
    declarations =
      Shorthand.deduplicate_declarations_with ~ctx rule.declarations;
  }

let rules ?scope (rules : rule list) : rule list =
  rules_aux ~ctx:(ctx_of_scope scope) ~enforce_spec:false ~owner:None
    ~supports:[] rules

(** {1 Nesting Flattening} *)

let flatten_nesting = Flatten.block

(** {1 Stylesheet Optimization} *)

(* Once an author supplied a prefix for a property, that spelling is theirs:
   synthesising another value could change what WebKit sees. Otherwise mirror
   every standard declaration so source-order fallback semantics stay intact. *)
let synthesise_declaration_prefixes ~normalize ~targets decls =
  let author_owns kind = List.exists (Webkit_fallback.is_prefixed kind) decls in
  let rec loop changed acc = function
    | [] -> if changed then List.rev acc else decls
    | decl :: rest -> (
        match Webkit_fallback.kind_of decl with
        | Some kind when not (author_owns kind) -> (
            match Webkit_fallback.of_declaration targets decl with
            | Some prefixed ->
                loop true (decl :: normalize prefixed :: acc) rest
            | None -> loop changed (decl :: acc) rest)
        | Some _ | None -> loop changed (decl :: acc) rest)
  in
  loop false [] decls

(* The next pass reads what this one writes. Its vendor-alias drop reads
   Baseline where the synthesis reads [targets], so it drops a twin written here
   as dead; a prefixed declaration of the same property that stays, one whose
   value the prefix spells differently, then makes the property the author's,
   and nothing writes the twin back. So what this writes is what that pass
   settles on: the twins the drop leaves, written again where no prefixed
   declaration of their property is left. The synthesis never runs under
   [enforce_spec], the one setting the drop reads. *)
let add_declaration_prefixes ~normalize ~targets decls =
  let written = synthesise_declaration_prefixes ~normalize ~targets decls in
  if written == decls then decls
  else
    let kept =
      Shorthand_dedup.drop_vendor_aliases ~ctx:Ctx.fragment
        (List.mapi (fun i decl -> (i, decl)) written)
    in
    if List.compare_lengths kept written = 0 then written
    else synthesise_declaration_prefixes ~normalize ~targets (List.map snd kept)

let rec condition_has_webkit kind = function
  | Supports.Property (Supports.Declaration (_, decl)) ->
      Webkit_fallback.is_prefixed kind decl
  | Supports.Property _ | Supports.Function _ | Supports.General_enclosed _ ->
      false
  | Supports.Not condition -> condition_has_webkit kind condition
  | Supports.And (a, b) | Supports.Or (a, b) ->
      condition_has_webkit kind a || condition_has_webkit kind b

let add_condition_prefixes ~targets condition =
  let author_owns kind = condition_has_webkit kind condition in
  let rec map = function
    | Supports.Property (Supports.Declaration (_, decl)) as original -> (
        match Webkit_fallback.kind_of decl with
        | Some kind when not (author_owns kind) -> (
            match Webkit_fallback.of_declaration targets decl with
            | Some prefixed ->
                (* Cascade writes this one, so it carries no authored
                   spelling. *)
                let name =
                  Supports.property_name (Declaration.property_name prefixed)
                in
                Supports.Or
                  ( Supports.Property (Supports.Declaration (name, prefixed)),
                    original )
            | None -> original)
        | Some _ | None -> original)
    | (Supports.Property _ | Supports.Function _ | Supports.General_enclosed _)
      as leaf ->
        leaf
    | Supports.Not condition as original ->
        let condition' = map condition in
        if condition' == condition then original else Supports.Not condition'
    | Supports.And (a, b) as original ->
        let a' = map a and b' = map b in
        if a' == a && b' == b then original else Supports.And (a', b')
    | Supports.Or (a, b) as original ->
        let a' = map a and b' = map b in
        if a' == a && b' == b then original else Supports.Or (a', b')
  in
  map condition

let rec add_conditional_prefixes ~targets = function
  | Media_condition _ as condition -> condition
  | Supports_condition_test condition as original ->
      let condition' = add_condition_prefixes ~targets condition in
      if condition' == condition then original
      else Supports_condition_test condition'
  | And (a, b) as original ->
      let a' = add_conditional_prefixes ~targets a
      and b' = add_conditional_prefixes ~targets b in
      if a' == a && b' == b then original else And (a', b')
  | Or (a, b) as original ->
      let a' = add_conditional_prefixes ~targets a
      and b' = add_conditional_prefixes ~targets b in
      if a' == a && b' == b then original else Or (a', b')

let compatibility_declaration_sites =
  {
    element_rule = true;
    animation_frame = true;
    page_box = true;
    position_fallback = true;
    condition_test = false;
  }

(* A twin can cover what an earlier rule of its run writes for the same
   selectors. [Rule.normalize] drops such a declaration, but it read the run
   before the twin existed, and no pass follows to read it again. So each run of
   [after] whose declarations the synthesis changed has its shadowing read once
   more: linear, and it moves no rule. [before] is the block the synthesis read,
   statement for statement. *)
let drop_shadowed_in_prefixed_runs ~floors ~before after =
  let flush acc run touched =
    let stmts = List.rev run in
    let rules =
      List.filter_map (function Rule r -> Some r | _ -> None) stmts
    in
    let kept = if touched then Rule.drop_shadowed ~floors rules else rules in
    if kept == rules then List.rev_append stmts acc
    else List.rev_append (List.map (fun r -> Rule r) kept) acc
  in
  let rec walk acc run touched before after =
    match (before, after) with
    | Rule b :: before, (Rule a as stmt) :: after ->
        walk acc (stmt :: run)
          (touched || a.declarations != b.declarations)
          before after
    | _ :: before, stmt :: after ->
        walk (stmt :: flush acc run touched) [] false before after
    | _ -> List.rev (flush acc run touched)
  in
  walk [] [] false before after

(* [normalize] is the pass's own normalisation, so a twin is written as the next
   pass would hold it. *)
let add_prefixes ~normalize ~targets stylesheet =
  let rewrite original =
    let stmt =
      match original with
      | Supports (condition, body) ->
          let condition' = add_condition_prefixes ~targets condition in
          if condition' == condition then original
          else Supports (condition', body)
      | Import ({ supports = Some condition; _ } as rule) ->
          let condition' = add_condition_prefixes ~targets condition in
          if condition' == condition then original
          else Import { rule with supports = Some condition' }
      | When (condition, body) ->
          let condition' = add_conditional_prefixes ~targets condition in
          if condition' == condition then original else When (condition', body)
      | Else (Some condition, body) ->
          let condition' = add_conditional_prefixes ~targets condition in
          if condition' == condition then original
          else Else (Some condition', body)
      | Else (None, _)
      | Rule _ | Declarations _ | Bang_comment _ | Charset _ | Import _
      | Namespace _ | Property _ | Layer_decl _ | Layer _ | Media _
      | Container _ | Moz_document _ | Starting_style _ | Supports_condition _
      | Origin _ | Scope _ | Keyframes _ | Webkit_keyframes _ | Moz_keyframes _
      | Font_face _ | Counter_style _ | Page _ | Page_with_margins _
      | Font_palette_values _ | Font_feature_values _ | View_transition _
      | Position_try _ | Viewport _ | Unknown_at_rule _ ->
          original
    in
    if at_declaration_site compatibility_declaration_sites stmt then
      map_statement_declarations
        (add_declaration_prefixes ~normalize ~targets)
        stmt
    else stmt
  in
  let rec block stmts =
    let stmts' =
      List.map_preserve
        (fun stmt -> map_statement_children block (rewrite stmt))
        stmts
    in
    if stmts' == stmts then stmts
    else drop_shadowed_in_prefixed_runs ~floors:targets ~before:stmts stmts'
  in
  block stylesheet

let add_compatibility_prefixes ~targets stylesheet =
  add_prefixes ~normalize:Declaration.normalize ~targets stylesheet

(** [drop_invalid] walks every declaration list in the stylesheet (rules, bare
    nesting blocks, [@keyframes] frames, [@page] and its margin boxes,
    [@position-try], [@supports-condition]) and removes declarations whose typed
    value contains an [Invalid] arm. *)
let drop_invalid (stylesheet : t) : t =
  map_declarations
    (List.filter_preserve (fun d -> not (Declaration.is_invalid d)))
    stylesheet

(* CSS Syntax 3 (ED) sec. 5.5.2 keeps an unrecognised at-rule's body as raw
   source text, so no typed node stands between the author's layout and the
   output and the serializer may not touch it: rewriting the body is an AST
   change. Reading it back as a component-value stream and writing it out with
   the separator rules that already serve custom-property streams keeps every
   token boundary, string, escape and nested block while the layout between them
   goes. A body the lexer cannot re-serialise to the same stream is left
   alone. *)
let compact_unknown_at_rule_body body =
  let reader = Reader.of_string body in
  let { Parser.value = components; warnings } =
    Parser.list_of_component_values reader
  in
  match warnings with
  | _ :: _ -> body
  | [] ->
      let compacted = Parser.to_string_minified components in
      if String.length compacted < String.length body then compacted else body

let compact_unknown_at_rule_bodies (stylesheet : t) : t =
  edit_statements
    (function
      | Unknown_at_rule ({ block = Some body; _ } as at) ->
          let compacted = compact_unknown_at_rule_body body in
          if String.equal compacted body then Keep
          else Replace (Unknown_at_rule { at with block = Some compacted })
      | _ -> Keep)
    stylesheet

(** [drop_unknown_at_rules] removes [Unknown_at_rule] statements at every block
    depth, matching what a user agent applies of a stylesheet (CSS 2.1 sec. 4.2)
    rather than what a transform may hand the next reader of one. Opt in when
    the output has exactly one consumer and it is a browser. *)
let drop_unknown_at_rules (stylesheet : t) : t =
  edit_statements (function Unknown_at_rule _ -> Drop | _ -> Keep) stylesheet

(* What a name's registration is, where every browser applies the same one. *)
type registration = { syntax : Variables.any_syntax; has_initial : bool }

(* CSS Properties and Values API 1 sec. 2.1: a name's registration is a
   [CSS.registerProperty()] record if there is one, else the last [@property]
   for it in document order. Only [`Stylesheet] scope rules out a script and
   another sheet, so a fragment knows none. A registration inside a conditional
   group rule applies only where the condition holds, so it leaves its name
   unknown, as does an [@property] the reader kept as an unknown at-rule:
   [--enforce-spec] keeps one that lacks a descriptor, which the current sec. 3
   reads as a registration and the shipping engines drop. [@layer] conditions
   nothing. *)
let known_registrations ~scope (stmts : statement list) :
    string -> registration option =
  match scope with
  | `Fragment -> fun _ -> None
  | `Stylesheet ->
      let tbl : (string, registration option) Hashtbl.t = Hashtbl.create 8 in
      let unknown (stmt : statement) =
        match stmt with
        | Property pr -> Hashtbl.replace tbl pr.name None
        | Unknown_at_rule { name; prelude; _ }
          when String.equal (String.lowercase_ascii name) "property" ->
            Hashtbl.replace tbl (String.trim prelude) None
        | _ -> ()
      in
      let rec top (stmt : statement) =
        match stmt with
        | Property pr ->
            Hashtbl.replace tbl pr.name
              (Some
                 {
                   syntax = Variables.Syntax pr.syntax;
                   has_initial = Option.is_some pr.initial_value;
                 })
        | Layer (_, block) -> List.iter top block
        | Unknown_at_rule _ -> unknown stmt
        | stmt -> iter_statements unknown [ stmt ]
      in
      List.iter top stmts;
      fun name -> Option.join (Hashtbl.find_opt tbl name)

(* CSS Properties and Values API 1 sec. 2: an [@property --name] registers a
   typed syntax, lifting [--name: ...] out of the opaque-token-stream rule, for
   a name whose registration is known ([known_registrations]). *)
let try_promote_custom_with (type a) (syntax : a Variables.syntax) components =
  match syntax with
  | Variables.Color -> Properties.try_read_custom_color components
  | Variables.Length -> Properties.try_read_custom_length components
  | Variables.Length_percentage ->
      Properties.try_read_custom_length_percentage components
  | Variables.Number -> Properties.try_read_custom_number components
  | Variables.Percentage -> Properties.try_read_custom_percentage components
  | Variables.Angle -> Properties.try_read_custom_angle components
  | Variables.Time -> Properties.try_read_custom_time components
  | _ -> None

let promote_registered_custom_decl ~lossless ~enforce_spec registry decl =
  match decl with
  | Declaration
      {
        property = Custom_property name;
        value = Custom_value { value = Tokens components; layer; meta };
        important;
        _;
      } -> (
      match (registry name : registration option) with
      | None -> decl
      | Some { syntax = Variables.Syntax syntax; _ } -> (
          match try_promote_custom_with syntax components with
          | Some typed ->
              Declaration.v ~important (Custom_property name)
                (Custom_value
                   {
                     value =
                       Properties.normalize_custom_property_value ~lossless
                         ~enforce_spec typed;
                     layer;
                     meta;
                   })
          | None -> decl))
  | _ -> decl

(* An [@property] registration is document-global regardless of source order
   (CSS Properties and Values API 1 sec. 2), and Tailwind emits its [@property]
   rules after the [@layer] that uses them, so the registry is read whole before
   any declaration is promoted. *)
let promote_registered_custom_properties ~lossless ~enforce_spec registry
    (stmts : statement list) =
  let promote_decls =
    List.map_preserve
      (promote_registered_custom_decl ~lossless ~enforce_spec registry)
  in
  (* A registration is document-global, so every declaration of that name is
     typed wherever it is written: through the declaration walker rather than a
     list of the at-rules that came to mind. *)
  map_declarations promote_decls stmts

(* HTML Living Standard sec. 15 (Rendering) gives these longhands a value other
   than their initial on some element, through its user-agent sheet or a
   presentational hint, among those a shorthand the optimizer composes resets:
   [font-weight] on headings, [b], [strong] and [th]; [font-style] on [i], [em],
   [cite], [var], [dfn] and [address]; [font-size] on headings, [small], [big],
   [sub] and [sup]; [font-family] on [pre], [code], [kbd], [samp] and [tt] and
   through [<font face>]; [background-color] on [mark] and through [bgcolor];
   [background-image] through a [background] attribute. Author beats user agent
   (CSS Cascade 5 sec. 6.2), so a shorthand resetting one of them overrides that
   value. *)
let user_agent_held_slots =
  List.concat_map
    (fun (Properties.Prop p) -> Shorthand_coverage.property_slot_keys p)
    Properties.
      [
        Prop Font_weight;
        Prop Font_style;
        Prop Font_size;
        Prop Font_family;
        Prop Background_color;
        Prop Background_image;
      ]

(* [Ctx.resets_held] under [`Stylesheet] scope: a shorthand composed from a run
   resets a slot something may hold when the user-agent sheet writes it, or a
   declaration of the sheet outside the run's rule does, in any rule or block.
   An [!important] one outranks a shorthand that is not, so it holds a slot only
   against an important shorthand. Each slot counts the declarations of the
   sheet that write it, so the rule's own are taken off; the composer judges
   those by their position. A declaration the footprint model cannot place may
   write any slot. *)
module Slot_count = Hashtbl.Make (struct
  type t = Shorthand_coverage.overlap_key * bool

  let equal (a, i) (b, j) =
    Shorthand_coverage.overlap_key_equal a b && Bool.equal i j

  let hash (k, i) = Hashtbl.hash (Shorthand_coverage.overlap_key_hash k, i)
end)

(* Count each slot's declarations by importance. One that holds only initial
   values drops nothing when reset. *)
let count_slots table d =
  if not (Shorthand_held.holds_only_initial d) then
    let important = Declaration.is_important d in
    List.iter
      (fun k ->
        let key = (k, important) in
        Slot_count.replace table key
          (1 + Option.value ~default:0 (Slot_count.find_opt table key)))
      (Shorthand_coverage.declaration_overlap_keys d)

let resets_held_of (stylesheet : t) =
  let count = Slot_count.create 256 in
  let (_ : t) =
    map_declarations
      (fun decls ->
        List.iter (count_slots count) decls;
        decls)
      stylesheet
  in
  fun ~rule run shorthand ->
    match Shorthand_coverage.reset_slots shorthand run with
    | [] -> false
    | reset ->
        let own = Slot_count.create 16 in
        List.iter (count_slots own) rule;
        let outside_of k important =
          let key = (k, important) in
          Option.value ~default:0 (Slot_count.find_opt count key)
          - Option.value ~default:0 (Slot_count.find_opt own key)
          > 0
        in
        let important = Declaration.is_important shorthand in
        let outside k =
          outside_of k false || (important && outside_of k true)
        in
        outside Shorthand_coverage.broad_overlap_key
        || List.exists
             (fun k ->
               List.exists
                 (Shorthand_coverage.overlap_key_equal k)
                 user_agent_held_slots
               || outside k)
             reset

(* Under closed-stylesheet scope every [@position-try --name] rule is known. A
   [position-try-fallbacks] entry whose name has no matching rule cannot match
   at runtime, so prune unknown [Name] arms (keeping [Flip_*] and [Var]). When
   every arm is pruned the whole declaration drops (equivalent to its
   initial). *)
let collect_position_try_names stylesheet =
  let known : (string, unit) Hashtbl.t = Hashtbl.create 8 in
  iter_statements
    (fun (stmt : statement) ->
      match stmt with
      | Position_try (name, _) -> Hashtbl.replace known name ()
      | _ -> ())
    stylesheet;
  known

let rec prune_position_try_decl known (decl : Declaration.declaration) :
    Declaration.declaration option =
  match decl with
  | Declaration
      {
        property = Position_try_fallbacks;
        value = (Fallbacks items : Properties.position_try_fallbacks);
        important;
        _;
      } -> (
      (* An entry names at most one [@position-try] rule; a position area and a
         tactics-only entry name none and always survive. *)
      let keep (entry : Properties.position_try_fallback_entry) =
        match entry with
        | Area _ -> true
        | Tactics group ->
            List.for_all
              (function
                | (Properties.Name s : Properties.position_try_fallback) ->
                    Hashtbl.mem known s
                | _ -> true)
              group
      in
      match List.filter_preserve keep items with
      | [] -> None
      | kept when kept == items -> Some decl
      | kept ->
          Some
            (Declaration.v ~important Position_try_fallbacks (Fallbacks kept)))
  | Theme_guarded { var_name; decl; _ } -> (
      match prune_position_try_decl known decl with
      | None -> None
      | Some decl' ->
          if decl' == decl then Some decl
          else Some (Declaration.theme_guarded ~var_name decl'))
  | other -> Some other

let prune_position_try_fallbacks ~scope (stylesheet : t) : t =
  match scope with
  | `Fragment -> stylesheet
  | `Stylesheet ->
      let known = collect_position_try_names stylesheet in
      let prune_decls decls =
        List.edit_preserve
          (fun decl ->
            match prune_position_try_decl known decl with
            | Some decl' when decl' == decl -> List.Keep
            | Some decl' -> List.Replace decl'
            | None -> List.Drop)
          decls
      in
      (* A name with no [@position-try] rule cannot match wherever it is
         written, so this goes through the declaration walker rather than a list
         of the at-rules that came to mind. *)
      map_declarations prune_decls stylesheet

(* A custom property whose known registration has an initial-value is never
   invalid at computed-value time, so folding its [var()] into a shorthand
   cannot widen a failure across the other longhands. [var()] references store
   the bare name and [@property] the [--] one. *)
let registered_foldable registry name =
  match
    (registry (Custom_property_name.add_prefix name) : registration option)
  with
  | Some { has_initial; _ } -> has_initial
  | None -> false

(* CSS Properties and Values API 1: a custom property registered with a
   single-component [@property] syntax (not a [+]/[#] list, [*], or a transform
   list) substitutes exactly one calc term, so a redundant [calc(var(--n))]
   nested in another [calc()] may be unwrapped. *)
let rec syntax_is_single_valued : type a. a Variables.syntax -> bool = function
  | Variables.Universal | Variables.Transform_list -> false
  | Variables.Plus _ | Variables.Hash _ -> false
  | Variables.Or (a, b) ->
      syntax_is_single_valued a && syntax_is_single_valued b
  | _ -> true

(* CSS Properties and Values API 1 sec. 2.4: a registered property always has a
   computed value matching its syntax, so a [<number>] or [<integer>]
   registration substitutes exactly one number. *)
let syntax_is_number : type a. a Variables.syntax -> bool = function
  | Variables.Number | Variables.Integer -> true
  | _ -> false

(* The calc-simplifier context of the known registrations. Calc [Var] leaves
   store the bare name and [@property] the [--] one. *)
let single_valued_calc_ctx registry : Values.calc_ctx =
  let syntax name =
    Option.map
      (fun r -> r.syntax)
      (registry (Custom_property_name.add_prefix name))
  in
  {
    Values.var_is_single_valued =
      (fun name ->
        match (syntax name : Variables.any_syntax option) with
        | Some (Variables.Syntax s) -> syntax_is_single_valued s
        | None -> false);
    var_is_number =
      (fun name ->
        match (syntax name : Variables.any_syntax option) with
        | Some (Variables.Syntax s) -> syntax_is_number s
        | None -> false);
    var_is_length =
      (fun name ->
        match (syntax name : Variables.any_syntax option) with
        | Some (Variables.Syntax Variables.Length) -> true
        | Some (Variables.Syntax _) | None -> false);
    budget = false;
  }

let normalize_live_declarations ~ctx ~lossless ~enforce_spec decls =
  List.edit_preserve
    (fun decl ->
      let decl' = Declaration.normalize ~ctx ~lossless ~enforce_spec decl in
      if Declaration.is_invalid decl' then List.Drop
      else if decl' == decl then List.Keep
      else List.Replace decl')
    decls

(* An [@property] registration holds a typed initial value rather than a
   declaration, so it is the one statement whose value
   [map_statement_declarations] does not reach; every other statement either
   carries an unknown at-rule's body as opaque source text, which has no grammar
   to normalise against, or has its declarations normalised wherever that walk
   finds them. *)
let sanitize_statement ~ctx ~lossless ~enforce_spec (s : statement) :
    statement edit =
  match s with
  | Unknown_at_rule _ -> Keep
  | Property r ->
      let initial_value =
        match r.initial_value with
        | None -> r.initial_value
        | Some value ->
            let value' =
              Variables.normalize_value ~lossless ~enforce_spec r.syntax value
            in
            if value' == value then r.initial_value else Some value'
      in
      if initial_value == r.initial_value then Keep
      else Replace (Property { r with initial_value })
  | _ ->
      let s' =
        map_statement_declarations
          (normalize_live_declarations ~ctx ~lossless ~enforce_spec)
          s
      in
      if s' == s then Keep else Replace s'

let sanitize_block ~ctx ~lossless ~enforce_spec (b : statement list) :
    statement list =
  edit_statements (sanitize_statement ~ctx ~lossless ~enforce_spec) b

(* One pass, and optimizing its output again returns it. Each rule run is
   factored once, its candidates and their acceptance reading the rules it
   prints ({!Factor.run}); every other step finishes what it starts in the same
   pass: a merge optimizes the blocks and runs it joins, a hoist joins the
   blocks it leaves adjacent, a dead nested rule takes the blocks it empties,
   and the prefixes are the ones the next pass would settle on. A pass that
   changes nothing hands back its input. *)
let run_pipeline ~ctx ~normalize ~targets ~enforce_spec stylesheet =
  let factor_cache = Factor.cache () in
  (* The prefixes come last: the vendor-alias drop reads {!Baseline} where the
     synthesis reads [targets], and the two disagree wherever a target trails
     Baseline, so a twin synthesised before the rule-local passes would be
     dropped there as dead. *)
  let prefixes stmts =
    if enforce_spec then stmts else add_prefixes ~normalize ~targets stmts
  in
  let result =
    prefixes (statements_top_level ~factor_cache ~ctx ~enforce_spec stylesheet)
  in
  if result == stylesheet || Stylesheet.equal result stylesheet then stylesheet
  else result

(* Bare names of every custom property referenced through [var()] in the tree.
   Scans the serialized declarations, so it sees references inside opaque values
   too and over-keeps (a [var(] inside a string counts): it must never miss a
   live reference, or the prune below drops a binding still in use. *)
let referenced_custom_props (stmts : statement list) : (string, unit) Hashtbl.t
    =
  let tbl = Hashtbl.create 64 in
  let bare = Custom_property_name.strip_prefix in
  let note_decls =
    List.iter (fun d ->
        List.iter
          (fun n -> Hashtbl.replace tbl (bare n) ())
          (Variables.var_refs_in_value_string
             (Declaration.to_string ~minify:true d)))
  in
  (* Through the exhaustive walk rather than a local match: a reference it
     cannot reach reads as no reference at all, and [@keyframes], [@page] and
     [@position-try] hold their declarations outside any block. *)
  iter_declarations note_decls stmts;
  tbl

(* Drop custom-property bindings referenced by no [var()] - a dead binding has
   no rendering effect (an emptied rule is removed at serialization). Caller
   opt-in only: the no-runtime-reader, complete-stylesheet assumption is theirs,
   like [Inline.vars]. *)
let drop_unused_custom_props (stmts : statement list) : statement list =
  let referenced = referenced_custom_props stmts in
  let bare = Custom_property_name.strip_prefix in
  let keep_decl d =
    match Variables.custom_declaration_name d with
    | Some name -> Hashtbl.mem referenced (bare name)
    | None -> true
  in
  let rec prune stmt =
    match stmt with
    | Rule r ->
        let declarations = List.filter_preserve keep_decl r.declarations in
        let nested = List.map_preserve prune r.nested in
        if declarations == r.declarations && nested == r.nested then stmt
        else Rule { r with declarations; nested }
    | Declarations decls ->
        let decls' = List.filter_preserve keep_decl decls in
        if decls' == decls then stmt else Declarations decls'
    | _ -> map_statement_children (List.map_preserve prune) stmt
  in
  List.map_preserve prune stmts

(* A nested form stays only where every target parses it; flattening is exact
   (CSS Nesting 1 sec. 4 and 5), so the rest is flattened first. *)
let flatten_unparsed_nesting ~flatten_nesting ctx stylesheet =
  if flatten_nesting || not (Ctx.parses_nesting ctx) then
    Flatten.block stylesheet
  else if Ctx.parses_nested_declarations ctx then stylesheet
  else Flatten.rules_with_nested_declarations stylesheet

let stylesheet ?scope ?(targets = evergreen_targets) ?judge
    ?(flatten_nesting = false) ?(lossless = false) ?(enforce_spec = false)
    ?(aggressive = false) ?(regroup = true) ?(closed_world = false)
    ?(objective = `Transfer) ?(prune_unused_custom_props = false) ?stats
    (stylesheet : t) : t =
  let scope = Option.value scope ~default:`Fragment in
  let registry = known_registrations ~scope stylesheet in
  let ctx = single_valued_calc_ctx registry in
  let stylesheet = sanitize_block ~ctx ~lossless ~enforce_spec stylesheet in
  let normalize = Declaration.normalize ~ctx ~lossless ~enforce_spec in
  let stylesheet = Stylesheet.drop_inert_at_rules stylesheet in
  (* Under [lossless] the raw body stands as authored: nothing types it, so
     nothing proves the layout inside it carries no meaning to its reader. *)
  let stylesheet =
    if lossless then stylesheet else compact_unknown_at_rule_bodies stylesheet
  in
  let stylesheet =
    promote_registered_custom_properties ~lossless ~enforce_spec registry
      stylesheet
  in
  let stylesheet = Stylesheet.normalize_shadow_color_vars stylesheet in
  let registered = registered_foldable registry in
  let stylesheet = prune_position_try_fallbacks ~scope stylesheet in
  let resets_held =
    match scope with
    | `Stylesheet -> resets_held_of stylesheet
    | `Fragment -> fun ~rule:_ _ _ -> true
  in
  let ctx =
    Ctx.v ~lossless ~aggressive ~regroup ~closed_world ~objective ~enforce_spec
      ~targets ?judge ~registered ~resets_held ?stats scope
  in
  let stylesheet = flatten_unparsed_nesting ~flatten_nesting ctx stylesheet in
  let result =
    run_pipeline
      ~ctx:(Ctx.with_extend_lists true ctx)
      ~normalize ~targets ~enforce_spec stylesheet
  in
  let result =
    if prune_unused_custom_props then drop_unused_custom_props result
    else result
  in
  let result = if flatten_nesting then Flatten.block result else result in
  Log.debug (fun m ->
      let c = (Stats.snapshot (Ctx.stats ctx)).counters in
      m "optimized: %d factoring fixpoints run, %d skipped, %d bytes saved"
        c.factor_fixpoints_run c.factor_fixpoints_skipped c.factor_bytes_saved);
  result