Source file rule_trace.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
(** The canonical form of a run of style rules and conditional blocks, read as
the trace of its declarations. *)
open Stylesheet
let declaration_text d = Pp.to_string ~minify:true Declaration.pp d
let selector_text sel = Pp.to_string ~minify:true Selector.pp sel
type condition =
| Media_condition of Media.t
| Supports_condition of Supports.t
| Container_condition of string option * Container.t
let negated_media : Media.t -> Media.t option = function
| Cond (Not c) -> Some (Cond c)
| Cond c -> Some (Cond (Not c))
| Type ({ prefix = None; _ } as q) ->
Some (Type { q with prefix = Some Media.Not })
| Type ({ prefix = Some Media.Not; _ } as q) ->
Some (Type { q with prefix = None })
| Type { prefix = Some Media.Only; _ } | List _ -> None
let excludes a b =
let negates negate equal x y =
match negate y with Some ny -> equal x ny | None -> false
in
match (a, b) with
| Media_condition x, Media_condition y ->
negates negated_media Media.equal x y
|| negates negated_media Media.equal y x
| Supports_condition x, Supports_condition y ->
Supports.equal x (Supports.Not y) || Supports.equal y (Supports.Not x)
| Container_condition (nx, x), Container_condition (ny, y) ->
Option.equal String.equal nx ny
&& (Container.equal x (Container.Not y)
|| Container.equal y (Container.Not x))
| _ -> false
type block_prelude =
| Media_query of Media.t
| Feature_query of Supports.t
| Container_query of string option * Container.t option
let block_of (stmt : statement) =
match stmt with
| Media (m, body) -> Some (Media_query m, body)
| Supports (c, body) -> Some (Feature_query c, body)
| Container (name, cond, body) -> Some (Container_query (name, cond), body)
| Rule _ | Declarations _ | Bang_comment _ | Charset _ | Import _
| Namespace _ | Property _ | Layer_decl _ | Layer _ | Moz_document _
| Starting_style _ | When _ | Else _ | 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 _ ->
None
let prelude_condition = function
| Media_query q -> Some (Media_condition q)
| Feature_query c -> Some (Supports_condition c)
| Container_query (None, Some (Container.Named (name, c))) ->
Some (Container_condition (Some name, c))
| Container_query (name, Some c) -> Some (Container_condition (name, c))
| Container_query (_, None) -> None
let block_statement prelude body =
match prelude with
| Media_query m -> Media (m, body)
| Feature_query c -> Supports (c, body)
| Container_query (name, cond) -> Container (name, cond, body)
module Prelude_key = struct
type shape =
| Text of string
| Container of string option * Container.t option
type t = { shape : shape; text : string }
let v prelude =
match prelude with
| Media_query m ->
let text = String.concat "" [ "@media "; Media.to_string m ] in
{ shape = Text text; text }
| Feature_query c ->
let text = String.concat "" [ "@supports "; Supports.to_string c ] in
{ shape = Text text; text }
| Container_query (name, cond) ->
let cond_text =
Option.fold ~none:""
~some:(fun c ->
Container.to_string ~minify:true (Container.normalize c))
cond
in
{
shape = Container (name, cond);
text =
String.concat " "
[ "@container"; Option.value ~default:"" name; cond_text ];
}
let equal a b =
String.equal a.text b.text
&&
match (a.shape, b.shape) with
| Text a, Text b -> String.equal a b
| Container (an, ac), Container (bn, bc) ->
Option.equal String.equal an bn && Option.equal Container.equal ac bc
| (Text _ | Container _), _ -> false
end
module Int_set = Set.Make (Int)
module Int_table = Hashtbl.Make (Int)
module Property_table = Hashtbl.Make (struct
type t = Declaration.prop_key
let equal = Declaration.equal_prop_key
let hash = Declaration.hash_prop_key
end)
type group = {
chain : (block_prelude * Prelude_key.t) array;
conditions : condition list;
template : rule;
name : string;
selector_key : string; (** the selector and the merge key *)
branches : Rule_graph.branches;
}
type entry = {
group : int;
decl : Declaration.declaration;
keys : Shorthand.overlap_key list;
text : string;
text_id : int; (** the same for two entries of one text *)
value : string Lazy.t;
property : int; (** the id of the property *)
unknown : bool; (** the model does not type the property *)
special : bool; (** a custom property or [all] *)
broad : bool; (** the footprint meets any key *)
important : bool;
mutable live : footprint option; (** [None] when no slot was rewritten *)
mutable dead : bool;
}
let rec unguarded = function
| Declaration.Theme_guarded { decl; _ } -> unguarded decl
| d -> d
let is_unknown d =
match unguarded d with
| Declaration.Declaration { property = Unknown_property _; _ } -> true
| _ -> false
let group_name chain selector =
let b = Buffer.create 64 in
Array.iter
(fun (_, (key : Prelude_key.t)) ->
Buffer.add_string b key.text;
Buffer.add_char b '{')
chain;
Buffer.add_string b (selector_text selector);
Buffer.contents b
let same_group (g : group) chain (r : rule) name =
String.equal g.name name
&& Array.length g.chain = Array.length chain
&& Array.for_all2 (fun (_, a) (_, b) -> Prelude_key.equal a b) g.chain chain
&& Option.equal String.equal g.template.merge_key r.merge_key
let rec element_chains acc stmt f =
match stmt with
| Rule r -> f (Array.of_list (List.rev acc)) r
| _ -> (
match block_of stmt with
| Some (prelude, body) ->
let acc = (prelude, Prelude_key.v prelude) :: acc in
List.iter (fun stmt -> element_chains acc stmt f) body
| None -> ())
type reader = {
parent : Selector.t option;
by_name : (string, group * int) Hashtbl.t;
mutable groups : group list;
mutable group_count : int;
ids : (string, int) Hashtbl.t;
properties : int Property_table.t;
mutable entries : entry list;
}
let property_id r decl =
let key =
match Declaration.property_key decl with
| Declaration.Key (Unknown_property { own = Some (Prop own); _ }) ->
Declaration.Key own
| key -> key
in
match Property_table.find_opt r.properties key with
| Some id -> id
| None ->
let id = Property_table.length r.properties in
Property_table.replace r.properties key id;
id
let text_id r text =
match Hashtbl.find_opt r.ids text with
| Some id -> id
| None ->
let id = Hashtbl.length r.ids in
Hashtbl.replace r.ids text id;
id
let group_of r chain (rule : rule) =
let name = group_name chain rule.selector in
match
List.find_opt
(fun (g, _) -> same_group g chain rule name)
(Hashtbl.find_all r.by_name name)
with
| Some (_, id) -> id
| None ->
let g =
{
chain;
conditions =
List.filter_map
(fun (prelude, _) -> prelude_condition prelude)
(Array.to_list chain);
template = rule;
name;
selector_key =
String.concat "\n"
[
selector_text rule.selector;
Option.value ~default:"" rule.merge_key;
];
branches = Rule_graph.branches_under ?parent:r.parent rule.selector;
}
in
let id = r.group_count in
r.group_count <- id + 1;
r.groups <- g :: r.groups;
Hashtbl.add r.by_name name (g, id);
id
let entry r ~group decl =
let text = declaration_text decl in
let keys = Shorthand.declaration_overlap_keys decl in
{
group;
decl;
keys;
text;
text_id = text_id r text;
value = lazy (Declaration.string_of_value ~minify:true decl);
property = property_id r decl;
unknown = is_unknown decl;
special =
Option.is_some (Shorthand.custom_property_name decl)
|| Shorthand.is_all_declaration (unguarded decl);
broad = Shorthand.overlap_keys_broad keys;
important = Declaration.is_important decl;
live = None;
dead = false;
}
let read_rule r chain (rule : rule) =
let group = group_of r chain rule in
List.iter
(fun decl -> r.entries <- entry r ~group decl :: r.entries)
rule.declarations
let rec keys_minus a b =
match (a, b) with
| [], _ -> []
| _, [] -> a
| x :: xs, y :: ys ->
let c = Shorthand.overlap_key_compare x y in
if c = 0 then keys_minus xs ys
else if c < 0 then x :: keys_minus xs b
else keys_minus a ys
let rec keys_within a b =
match (a, b) with
| [], _ -> true
| _ :: _, [] -> false
| x :: xs, y :: ys ->
let c = Shorthand.overlap_key_compare x y in
if c = 0 then keys_within xs ys else c > 0 && keys_within a ys
let narrowable d =
(not (Shorthand.is_intentionally_duplicated d))
&&
match d with
| Declaration.Theme_guarded _ -> false
| Declaration.Declaration { property; _ }
when Properties.is_vendor_prefixed property ->
false
| Declaration.Declaration { property = Custom_property _; _ } -> false
| Declaration.Declaration { property = Unknown_property _; _ } ->
Shorthand.declaration_is_broad d
| Declaration.Declaration _ -> true
let deduplicated ~ctx d first second =
not
(List.memq d
(Shorthand.deduplicate_declarations_with ~ctx ~merge_box:false
[ first; second ]))
let vendor_prefixed d =
match unguarded d with
| Declaration.Declaration { property; _ } ->
Properties.is_vendor_prefixed property
| Declaration.Theme_guarded _ -> false
let overrides x p y q =
q <> p
&& ((y.important && not x.important)
|| (Bool.equal y.important x.important && q > p))
let kill_entry ~ctx entries members p =
let x = entries.(members.(p)) in
let rewritten = ref [] in
Array.iteri
(fun q yi ->
let y = entries.(yi) in
if (not x.dead) && (not y.dead) && overrides x p y q then
if Declaration.same_property x.decl y.decl then begin
let first, second = if q > p then (x, y) else (y, x) in
if
(q > p && Int.equal x.text_id y.text_id)
|| deduplicated ~ctx x.decl first.decl second.decl
then x.dead <- true
end
else if
q > p
&& List.equal Shorthand.overlap_key_equal x.keys y.keys
&& (not (vendor_prefixed y.decl))
&& deduplicated ~ctx x.decl x.decl y.decl
then x.dead <- true
else if Shorthand.overlap_keys_intersect x.keys y.keys then
rewritten :=
List.rev_append
(Shorthand.declaration_slot_keys
~enforce_spec:(Ctx.enforce_spec ctx) y.decl)
!rewritten)
members;
match !rewritten with
| [] -> ()
| _ when x.dead || not (narrowable x.decl) -> ()
| rewritten -> (
let rewritten = List.sort_uniq Shorthand.overlap_key_compare rewritten in
if x.broad then x.live <- Some (Broad_except rewritten)
else
match keys_minus x.keys rewritten with
| [] -> x.dead <- true
| rest when List.compare_lengths rest x.keys = 0 -> ()
| rest -> x.live <- Some (Spelled rest))
let kill ~ctx entries members =
Array.iteri (fun p _ -> kill_entry ~ctx entries members p) members
let e =
match e.live with
| Some f -> f
| None -> if e.broad then Broad_except [] else Spelled e.keys
let live_meet x y =
match (x.live, y.live) with
| None, None -> true
| _ -> (
match (footprint x, footprint y) with
| Spelled a, Spelled b -> Shorthand.overlap_keys_intersect a b
| Spelled a, Broad_except k | Broad_except k, Spelled a ->
not (keys_within a k)
| Broad_except _, Broad_except _ -> true)
type lasts = { texts : int array; last : int array }
type order = {
groups : group array;
entries : entry array;
met_pairs : int array;
met : bool array;
mutable twins : lasts array;
(** by group, the last live entry of each text ({!twin}) *)
unknown_meet : bool Int_table.t; (** by pair of untyped property names *)
}
let pair_slots n =
let rec grow slots =
if slots >= 4 * n || slots >= 4096 then slots else grow (2 * slots)
in
grow 16
let ask pairs answers n a b f =
let a, b = if a < b then (a, b) else (b, a) in
let pair = (a * n) + b in
let slot = Hashtbl.hash pair land (Array.length pairs - 1) in
if Int.equal pairs.(slot) pair then answers.(slot)
else begin
let answer = f a b in
pairs.(slot) <- pair;
answers.(slot) <- answer;
answer
end
let groups_meet o a b =
Int.equal a b
|| ask o.met_pairs o.met (Array.length o.groups) a b (fun a b ->
let ga = o.groups.(a) and gb = o.groups.(b) in
(not
(List.exists
(fun c -> List.exists (excludes c) gb.conditions)
ga.conditions))
&& Rule_graph.branches_conflict ga.branches gb.branches)
let rec last_after lasts id k lo hi =
lo < hi
&&
let mid = (lo + hi) / 2 in
let c = Int.compare lasts.texts.(mid) id in
if c = 0 then lasts.last.(mid) > k
else if c < 0 then last_after lasts id k (mid + 1) hi
else last_after lasts id k lo mid
let later twins o k other =
let lasts = twins.(o.entries.(k).group) in
last_after lasts o.entries.(other).text_id k 0 (Array.length lasts.texts)
let twin twins o i j = later twins o i j || later twins o j i
let twins entries members =
Array.map
(fun m ->
let live =
List.filter (fun i -> not entries.(i).dead) (Array.to_list m)
in
let by_text =
List.stable_sort
(fun a b -> Int.compare entries.(a).text_id entries.(b).text_id)
live
in
let rec lasts = function
| a :: (b :: _ as rest)
when Int.equal entries.(a).text_id entries.(b).text_id ->
lasts rest
| a :: rest -> a :: lasts rest
| [] -> []
in
let picked = Array.of_list (lasts by_text) in
{ texts = Array.map (fun i -> entries.(i).text_id) picked; last = picked })
members
let same_write x y =
(not (Declaration.same_property x.decl y.decl))
&& List.equal Shorthand.overlap_key_equal x.keys y.keys
&& String.equal (Lazy.force x.value) (Lazy.force y.value)
let overlap o x y =
if x.unknown && y.unknown then begin
let a, b =
if x.property < y.property then (x.property, y.property)
else (y.property, x.property)
in
let pair = (a lsl 31) lor b in
match Int_table.find_opt o.unknown_meet pair with
| Some meet -> meet
| None ->
let meet =
Shorthand.declarations_overlap_with_keys x.decl x.keys y.decl y.keys
in
Int_table.replace o.unknown_meet pair meet;
meet
end
else if (x.unknown || y.unknown) && not (x.special || y.special) then
Shorthand.overlap_keys_intersect x.keys y.keys
else Shorthand.declarations_overlap_with_keys x.decl x.keys y.decl y.keys
let differ x y =
x.unknown || y.unknown
|| Shorthand.declarations_conflict_with_keys x.decl x.keys y.decl y.keys
let settled_meet o i j x y = live_meet x y && not (twin o.twins o i j)
let crosses o i j x y =
(not (Int.equal x.text_id y.text_id))
&& overlap o x y
&& groups_meet o x.group y.group
&& settled_meet o i j x y && differ x y
&& not (same_write x y)
let depends o i j =
let x = o.entries.(i) and y = o.entries.(j) in
Bool.equal x.important y.important
&& if Int.equal x.group y.group then overlap o x y else crosses o i j x y
type bucket_kind = Key of Shorthand.overlap_key | Broad | Every | Unknown
module Bucket = Hashtbl.Make (struct
type t = bucket_kind * int * bool
let equal (ka, sa, ia) (kb, sb, ib) =
Int.equal sa sb && Bool.equal ia ib
&&
match (ka, kb) with
| Key a, Key b -> Shorthand.overlap_key_equal a b
| Broad, Broad | Every, Every | Unknown, Unknown -> true
| (Key _ | Broad | Every | Unknown), _ -> false
let hash (k, s, i) =
let k =
match k with
| Key key -> Shorthand.overlap_key_hash key
| Broad -> 1
| Every -> 2
| Unknown -> 3
in
Hashtbl.hash (k, s, i)
end)
type positions = { mutable items : int array; mutable size : int }
let push bucket i =
if bucket.size = Array.length bucket.items then begin
let grown = Array.make (max 8 (2 * bucket.size)) 0 in
Array.blit bucket.items 0 grown 0 bucket.size;
bucket.items <- grown
end;
bucket.items.(bucket.size) <- i;
bucket.size <- bucket.size + 1
let specificity_code ({ ids; classes; elements } : Selector.specificity) =
(ids lsl 40) lor (classes lsl 20) lor elements
let bucket buckets key =
match Bucket.find_opt buckets key with
| Some b -> b
| None ->
let b = { items = [||]; size = 0 } in
Bucket.replace buckets key b;
b
let buckets_of o buckets e =
let read = ref [] and filed = ref [] in
let specs =
List.sort_uniq Int.compare
(List.map specificity_code
(Rule_graph.branch_specificities o.groups.(e.group).branches))
in
List.iter
(fun spec ->
let at kind = bucket buckets (kind, spec, e.important) in
let keys = List.map (fun k -> at (Key k)) e.keys in
if e.broad then begin
read := at Every :: !read;
filed := at Broad :: !filed
end
else begin
read := at Broad :: List.rev_append keys !read;
filed := List.rev_append keys !filed
end;
filed := at Every :: !filed;
if e.unknown then begin
read := at Unknown :: !read;
filed := at Unknown :: !filed
end)
specs;
(Array.of_list !read, !filed)
let rec next_candidate read cursor stamp j =
let best = ref (-1) and at = ref (-1) in
for k = 0 to Array.length read - 1 do
let c = cursor.(k) in
if c >= 0 && read.(k).items.(c) > !at then begin
best := k;
at := read.(k).items.(c)
end
done;
if !best < 0 then -1
else begin
cursor.(!best) <- cursor.(!best) - 1;
if stamp.(!at) = j then next_candidate read cursor stamp j
else begin
stamp.(!at) <- j;
!at
end
end
let closure_limit = 16384
let covered_limit = 8
let rec covered o i k = function
| [] -> false
| _ when k = 0 -> false
| l :: rest -> depends o i l || covered o i (k - 1) rest
let order_graph o =
let n = Array.length o.entries in
let succ = Array.make n [] and preds = Array.make n 0 in
let buckets = Bucket.create 64 and stamp = Array.make n (-1) in
let ancestors =
if n <= closure_limit then Array.make n Bytes.empty else [||]
in
Array.iteri
(fun j e ->
if not e.dead then begin
let read, filed = buckets_of o buckets e in
let cursor = Array.map (fun b -> b.size - 1) read in
let link i =
succ.(i) <- j :: succ.(i);
preds.(j) <- preds.(j) + 1
in
(if Array.length ancestors > 0 then begin
let reach = Reach.v n in
ancestors.(j) <- reach;
let rec walk () =
let i = next_candidate read cursor stamp j in
if i >= 0 then begin
if (not (Reach.mem reach i)) && depends o i j then begin
link i;
Reach.union ~into:reach ancestors.(i);
Reach.add reach i
end;
walk ()
end
in
walk ()
end
else
let rec walk linked =
let i = next_candidate read cursor stamp j in
if i >= 0 then
if (not (covered o i covered_limit linked)) && depends o i j then begin
link i;
walk (i :: linked)
end
else walk linked
in
walk []);
List.iter (fun b -> push b j) filed
end)
o.entries;
(succ, preds)
type emission = {
o : order;
succ : int list array;
preds : int array;
outside : int array;
leads : bool array;
by_text : int array;
text_rank : int array;
by_name : int array;
name_rank : int array;
remaining : int array;
waiting : int array;
ready : Int_set.t array;
ready_leading : Int_set.t array;
mutable free : Int_set.t;
mutable leading : Int_set.t;
}
let ranked n compare =
let order = Array.init n Fun.id in
Array.sort
(fun a b -> match compare a b with 0 -> Int.compare a b | c -> c)
order;
let rank = Array.make n 0 in
Array.iteri (fun r i -> rank.(i) <- r) order;
(order, rank)
let group_of_entry s i = s.o.entries.(i).group
let mark_ready s i =
let g = group_of_entry s i in
s.ready.(g) <- Int_set.add s.text_rank.(i) s.ready.(g);
if s.leads.(i) then begin
if Int_set.is_empty s.ready_leading.(g) then
s.leading <- Int_set.add s.name_rank.(g) s.leading;
s.ready_leading.(g) <- Int_set.add s.text_rank.(i) s.ready_leading.(g)
end
let start o (succ, preds) =
let n = Array.length o.entries and ng = Array.length o.groups in
let group i = o.entries.(i).group in
let by_text, text_rank =
ranked n (fun a b -> String.compare o.entries.(a).text o.entries.(b).text)
in
let by_name, name_rank =
ranked ng (fun a b -> String.compare o.groups.(a).name o.groups.(b).name)
in
let leads = Array.make n false and outside = Array.make n 0 in
for i = n - 1 downto 0 do
List.iter
(fun s ->
if group s <> group i then outside.(s) <- outside.(s) + 1;
if group s <> group i || leads.(s) then leads.(i) <- true)
succ.(i)
done;
let s =
{
o;
succ;
preds;
outside;
leads;
by_text;
text_rank;
by_name;
name_rank;
remaining = Array.make ng 0;
waiting = Array.make ng 0;
ready = Array.make ng Int_set.empty;
ready_leading = Array.make ng Int_set.empty;
free = Int_set.empty;
leading = Int_set.empty;
}
in
Array.iteri
(fun i e ->
if not e.dead then begin
s.remaining.(e.group) <- s.remaining.(e.group) + 1;
if outside.(i) > 0 then s.waiting.(e.group) <- s.waiting.(e.group) + 1;
if preds.(i) = 0 then mark_ready s i
end)
o.entries;
Array.iteri
(fun g left ->
if left > 0 && s.waiting.(g) = 0 then
s.free <- Int_set.add s.name_rank.(g) s.free)
s.remaining;
s
let release s g j =
let h = group_of_entry s j in
s.preds.(j) <- s.preds.(j) - 1;
if h <> g then begin
s.outside.(j) <- s.outside.(j) - 1;
if s.outside.(j) = 0 then begin
s.waiting.(h) <- s.waiting.(h) - 1;
if s.waiting.(h) = 0 then s.free <- Int_set.add s.name_rank.(h) s.free
end
end;
if s.preds.(j) = 0 then mark_ready s j
let take s i =
let g = group_of_entry s i in
s.remaining.(g) <- s.remaining.(g) - 1;
if s.remaining.(g) = 0 then s.free <- Int_set.remove s.name_rank.(g) s.free;
s.ready.(g) <- Int_set.remove s.text_rank.(i) s.ready.(g);
if s.leads.(i) then begin
s.ready_leading.(g) <- Int_set.remove s.text_rank.(i) s.ready_leading.(g);
if Int_set.is_empty s.ready_leading.(g) then
s.leading <- Int_set.remove s.name_rank.(g) s.leading
end;
List.iter (release s g) s.succ.(i)
let piece s g from =
let rec go acc =
match Int_set.min_elt_opt from.(g) with
| None -> List.rev acc
| Some r ->
let i = s.by_text.(r) in
take s i;
go (s.o.entries.(i).decl :: acc)
in
go []
let emit o graph =
let s = start o graph in
let rec go pieces =
let next =
match Int_set.min_elt_opt s.free with
| Some r -> Some (s.by_name.(r), s.ready)
| None ->
Option.map
(fun r -> (s.by_name.(r), s.ready_leading))
(Int_set.min_elt_opt s.leading)
in
match next with
| None ->
if Array.exists (fun left -> left > 0) s.remaining then
invalid_arg "Rule_trace.emit: an entry left with none to take"
else List.rev pieces
| Some (g, from) -> (
let decls = piece s g from in
match pieces with
| (h, before) :: rest when Int.equal h g ->
go ((g, before @ decls) :: rest)
| _ -> go ((g, decls) :: pieces))
in
go []
let rec statements_of o depth = function
| [] -> []
| (g, declarations) :: rest when Array.length o.groups.(g).chain = depth ->
Rule { o.groups.(g).template with declarations }
:: statements_of o depth rest
| (g, _) :: _ as pieces ->
let prelude, key = o.groups.(g).chain.(depth) in
let under (h, _) =
let chain = o.groups.(h).chain in
Array.length chain > depth && Prelude_key.equal (snd chain.(depth)) key
in
let rec split acc = function
| p :: rest when under p -> split (p :: acc) rest
| rest -> (List.rev acc, rest)
in
let inside, rest = split [] pieces in
block_statement prelude (statements_of o (depth + 1) inside)
:: statements_of o depth rest
let descendants succ seen x y =
let visited = ref [] in
let rec walk = function
| [] -> ()
| i :: rest ->
if i >= y || seen.(i) then walk rest
else begin
seen.(i) <- true;
visited := i :: !visited;
walk (List.rev_append succ.(i) rest)
end
in
walk (List.filter (fun s -> not (Int.equal s y)) succ.(x));
List.iter (fun i -> seen.(i) <- false) !visited;
!visited
let between ~counts succ seen x y =
let leads_to_y i = List.exists (Int.equal y) succ.(i) in
List.exists
(fun z ->
counts z
&& (leads_to_y z || List.exists leads_to_y (descendants succ seen z y)))
(descendants succ seen x y)
let dedup_twin ~ctx ex ey before =
List.equal Shorthand.overlap_key_equal ex.keys ey.keys
&& (not (Int.equal ex.property ey.property))
&& String.equal (Lazy.force ex.value) (Lazy.force ey.value)
&& List.is_empty
(Shorthand.declaration_slot_keys ~enforce_spec:(Ctx.enforce_spec ctx)
ey.decl)
&& not
(List.memq ey.decl
(Shorthand.deduplicate_declarations_with ~ctx ~merge_box:false
(Lazy.force before @ [ ey.decl ])))
let group_from o members x y =
let m = members.(o.entries.(x).group) in
let rec first lo hi =
if lo >= hi then lo
else
let mid = (lo + hi) / 2 in
if m.(mid) < x then first (mid + 1) hi else first lo mid
in
let rec collect k acc =
if k >= Array.length m || m.(k) >= y then List.rev acc
else
let e = o.entries.(m.(k)) in
collect (k + 1) (if e.dead then acc else e.decl :: acc)
in
collect (first 0 (Array.length m)) []
let supports ~ctx o members holders x y =
let ey = o.entries.(y) in
let names_a_slot =
not
(List.is_empty
(Shorthand.declaration_slot_keys ~enforce_spec:(Ctx.enforce_spec ctx)
ey.decl))
in
let twinned =
lazy
(List.exists
(fun g -> (not (Int.equal g ey.group)) && groups_meet o g ey.group)
(Option.value ~default:[] (Int_table.find_opt holders ey.text_id)))
in
let orders p =
let ep = o.entries.(p) in
let later = p < y && Bool.equal ep.important ey.important in
let overrides = later || (ey.important && not ep.important) in
names_a_slot && overrides
&& Shorthand.overlap_keys_intersect ep.keys ey.keys
|| (later && overlap o ep ey && Lazy.force twinned)
in
Array.exists
(fun p -> p <> y && p <> x && (not o.entries.(p).dead) && orders p)
members.(ey.group)
let holders entries =
let t = Int_table.create 256 in
Array.iter
(fun e ->
if not e.dead then
let gs = Option.value ~default:[] (Int_table.find_opt t e.text_id) in
if not (List.exists (Int.equal e.group) gs) then
Int_table.replace t e.text_id (e.group :: gs))
entries;
t
let repeats ~ctx o members holders graph seen x y =
let ex = o.entries.(x) and ey = o.entries.(y) in
(not ex.dead)
&& (not (Int.equal x y))
&&
if Int.equal ex.group ey.group then
x < y
&& dedup_twin ~ctx ex ey (lazy (group_from o members x y))
&& (not (supports ~ctx o members holders x y))
&& not
(between
~counts:(fun z -> not (Int.equal o.entries.(z).group ey.group))
(fst (Lazy.force graph))
seen x y)
else
(Int.equal ex.text_id ey.text_id
|| dedup_twin ~ctx ex ey (Lazy.from_val [ ex.decl ]))
&& (not (supports ~ctx o members holders x y))
&& (x > y
|| not
(between ~counts:(fun _ -> true) (fst (Lazy.force graph)) seen x y)
)
let drop_repeats ~ctx o graph members unconditional =
let seen = Array.make (Array.length o.entries) false in
let holders = holders o.entries in
let dropped = ref false in
let by_depth = Array.init (Array.length o.groups) Fun.id in
Array.stable_sort
(fun a b ->
Int.compare
(Array.length o.groups.(a).chain)
(Array.length o.groups.(b).chain))
by_depth;
Array.iter
(fun g ->
let witnesses =
if Array.length o.groups.(g).chain = 0 then members.(g)
else
match Hashtbl.find_opt unconditional o.groups.(g).selector_key with
| Some h -> Array.append members.(h) members.(g)
| None -> members.(g)
in
let decide important y =
if
Bool.equal o.entries.(y).important important
&& (not o.entries.(y).dead)
&& Array.exists
(fun x -> repeats ~ctx o members holders graph seen x y)
witnesses
then begin
o.entries.(y).dead <- true;
dropped := true
end
in
Array.iter (decide false) members.(g);
Array.iter (decide true) members.(g))
by_depth;
!dropped
let read ~ctx ?parent stmts =
let r =
{
parent;
by_name = Hashtbl.create 64;
groups = [];
group_count = 0;
ids = Hashtbl.create 256;
properties = Property_table.create 64;
entries = [];
}
in
List.iter (fun stmt -> element_chains [] stmt (read_rule r)) stmts;
let entries = Array.of_list (List.rev r.entries) in
let groups = Array.of_list (List.rev r.groups) in
let members = Array.make (Array.length groups) [] in
for i = Array.length entries - 1 downto 0 do
let e = entries.(i) in
members.(e.group) <- i :: members.(e.group)
done;
let members = Array.map Array.of_list members in
Array.iter (kill ~ctx entries) members;
( members,
{
groups;
entries;
met_pairs = Array.make (pair_slots (Array.length groups)) (-1);
met = Array.make (pair_slots (Array.length groups)) false;
twins = twins entries members;
unknown_meet = Int_table.create 16;
} )
let settle ~ctx ?parent ?(drops = true) stmts =
let members, o = read ~ctx ?parent stmts in
let unconditional = Hashtbl.create 16 in
Array.iteri
(fun g group ->
if Array.length group.chain = 0 then
Hashtbl.replace unconditional group.selector_key g)
o.groups;
if drops && drop_repeats ~ctx o (lazy (order_graph o)) members unconditional
then o.twins <- twins o.entries members;
statements_of o 0 (emit o (order_graph o))