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
open! Core
open Css_parser_common
module Token = Css_parser_common.Token
open Types
let rec consume_list_of_rules tokens =
let rules_with_loc =
Parse_queue.with_loc
~context:(Some Rules)
~f:
(Parse_queue.process_into_list ~while_:(Not (Is EOF)) ~f:(function
| WHITESPACE _ | CDO | CDC | SEMICOLON -> None
| COMMENT ->
let loc = Parse_queue.dequeue_exn tokens |> Location.from_token in
Some (Rule.Comment (comment, loc))
| AT_KEYWORD _ -> Some (At_rule (consume_at_rule tokens))
| _ -> Some (Style_rule (consume_style_rule tokens))))
tokens
in
match rules_with_loc with
| None ->
(match Parse_queue.to_list tokens with
| [] ->
Parse_queue.raise_no_location
"Tried to parse but received empty queue of tokens. This is a parse error, \
please contact the maintainers of the CSS parser"
| [ (Token.EOF, loc) ] -> [], loc
| remaining_tokens ->
let remaining_tokens =
List.map
~f:(fun (token, loc) -> [%string "%{token#Token} (%{loc#Location})"])
remaining_tokens
|> String.concat ~sep:"\n"
in
Parse_queue.raise_no_location
[%string
"Didn't parse anything but token queue is not empty.\n\
\ Remaining tokens: %{remaining_tokens}"])
| Some (rules, loc) -> rules, loc
and consume_style_rule tokens =
let selectors =
Parse_queue.with_loc_exn
~f:(consume_complex_selector_list ~list_terminator:Token.is_left_brace)
tokens
in
let style_block = Parse_queue.with_loc_exn ~f:consume_style_block tokens in
let loc = Location.merge ~start:(snd selectors) ~end_:(snd style_block) in
{ Style_rule.selectors; block = style_block; loc }
and is_declaration_or_qualified_rule tokens =
Parse_queue.fold_until
~init:`Neither
~finish:(fun _ -> `Declaration `Definite)
~f:(fun seen (token, _) ->
match seen with
| `Neither ->
(match token with
| WHITESPACE _ | COMMENT _ -> Continue `Neither
| IDENT _ -> Continue `Ident
| _ -> Stop `Qualified_rule)
| `Ident ->
(match token with
| WHITESPACE _ | COMMENT _ -> Continue `Ident
| COLON -> Continue (`Ident_and_colon `Just_seen)
| _ -> Stop `Qualified_rule)
| `Ident_and_colon processing_state ->
let continue = Continue_or_stop.Continue (`Ident_and_colon `Stale) in
(match token with
| WHITESPACE _ | COMMENT _ ->
(match processing_state with
| `Just_seen -> Stop (`Declaration `Definite)
| `Stale -> continue)
| SEMICOLON -> Stop (`Declaration `Definite)
| RIGHT_BRACE -> Stop (`Declaration `Maybe_selector)
| LEFT_BRACE -> Stop `Qualified_rule
| EOF -> Stop (`Declaration `Maybe_selector)
| _ -> continue))
tokens
and consume_style_block_contents ~while_ tokens =
Parse_queue.with_context
Block
~f:(fun tokens ->
Parse_queue.process_into_list tokens ~while_ ~f:(function
| SEMICOLON | WHITESPACE _ -> None
| COMMENT ->
let loc = Parse_queue.dequeue_exn tokens |> Location.from_token in
Some (Style_block.Block_element.Comment (comment, loc))
| AT_KEYWORD _ ->
let at_rule =
Parse_queue.with_loc_exn ~f:(fun tokens -> consume_at_rule tokens) tokens
|> Tuple2.map_fst ~f:(fun rule -> Rule.At_rule rule)
in
Some (Rule at_rule)
| _ ->
(match is_declaration_or_qualified_rule tokens with
| `Declaration ambiguity ->
let declaration =
Parse_queue.with_loc_exn
~f:(fun tokens -> consume_declaration ~ambiguity tokens)
tokens
in
Some (Declaration declaration)
| `Qualified_rule ->
let rule =
Parse_queue.with_loc_exn ~f:consume_style_rule tokens
|> Tuple2.map_fst ~f:(fun rule -> Rule.Style_rule rule)
in
Some (Rule rule))))
tokens
and consume_style_block tokens =
Parse_queue.require_next_token_to_match_and_ignore
tokens
~matches:(Is LEFT_BRACE)
~error_msg:(fun _ -> "Error while parsing style block. Expected opening left brace");
let rules =
consume_style_block_contents ~while_:(Not (Any [ Is RIGHT_BRACE; Is EOF ])) tokens
in
Parse_queue.require_next_token_to_match_and_ignore
tokens
~matches:(Is RIGHT_BRACE)
~error_msg:(fun _ -> "Error while parsing style block. Expected closing right brace");
rules
and matches_namespace_separator tokens =
Parse_queue.fold_until
tokens
~init:`Init
~f:(fun acc (token, _loc) ->
match acc, token with
| `Init, DELIM "|" -> Continue `Maybe_valid_namespace
| `Maybe_valid_namespace, DELIM "|" -> Stop `Not_namespace
| `Maybe_valid_namespace, (WHITESPACE _ | COMMENT _) -> Stop `Trailing_invalid
| `Maybe_valid_namespace, (IDENT _ | DELIM "*") -> Stop `Valid_namespace
| (`Init | `Whitespace_or_comment), (WHITESPACE _ | COMMENT _) ->
Continue `Whitespace_or_comment
| `Whitespace_or_comment, DELIM "|" -> Continue `Detached_pipe
| `Detached_pipe, DELIM "|" -> Stop `Not_namespace
| `Detached_pipe, _ -> Stop `Leading_invalid
| _ -> Stop `Not_namespace)
~finish:(fun _ -> `Not_namespace)
and consume_type_selector tokens =
let get_type_selector_part tokens =
match Parse_queue.dequeue_exn tokens with
| IDENT ident, _ -> Ident_like.to_string ident
| DELIM "*", _ -> "*"
| token, loc ->
Parse_queue.raise
~loc
[%string
"Error while parsing type selector. Expected an identifier or an asterisk, but \
found: %{token#Token}"]
in
let first_type_selector_part = get_type_selector_part tokens in
match matches_namespace_separator tokens with
| `Not_namespace -> Selector.Type (first_type_selector_part, None)
| `Trailing_invalid ->
Parse_queue.dequeue_exn tokens
|> Parse_queue.throw_error_for_token ~f:(fun _ ->
"Comments and/or whitespaces are not allowed directly after a namespace separator")
| `Leading_invalid ->
Parse_queue.dequeue_exn tokens
|> Parse_queue.throw_error_for_token ~f:(fun _ ->
"Comments and/or whitespaces are not allowed directly before a namespace separator")
| `Valid_namespace ->
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Equals (DELIM "|"))
~error_msg:(fun _ ->
"Expected a namespace separator. This is an error within the logic of the CSS \
parser, please contact the maintainers of the parser.")
tokens;
let type_selector = get_type_selector_part tokens in
Selector.Type (type_selector, Some first_type_selector_part)
and parse_pseudo_class_like_selector ~kind tokens =
let kind_string =
match kind with
| `Pseudoclass -> "pseudoclass"
| `Pseudoelement -> "pseudoelement"
in
let error_msg = lazy [%string "Error while parsing %{kind_string} selector."] in
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Is COLON)
~error_msg:(fun _ ->
match kind with
| `Pseudoelement ->
[%string
"%{force error_msg} Expected to parse a pseudoelement but missing second \
colon. This is potentially an error in the CSS parser, please contact the \
maintainers of the parser."]
| `Pseudoclass ->
[%string
"%{force error_msg} %{String.capitalize kind_string} selector must start with \
a colon"])
tokens;
match Parse_queue.dequeue_exn ~error_msg tokens with
| (COMMENT _, _) as ->
Parse_queue.throw_error_for_token comment ~f:(fun _ ->
[%string
"%{force error_msg} Comments should not occur between parts of a %{kind_string} \
selector"])
| IDENT ident, _ -> Pseudoclass_element_selector.Ident (Ident_like.to_string ident)
| (FUNCTION fn, _) as fn_token ->
let fn = Ident_like.to_string fn in
let pseudoclass_functions_with_selectors_matches_fn =
List.mem
~equal:[%equal: string]
[ "has"; "is"; "where"; "not" ]
(String.lowercase fn)
in
let fn_name_with_loc = fn, Location.from_token fn_token in
(match kind, `Match_pseudoclass pseudoclass_functions_with_selectors_matches_fn with
| `Pseudoclass, `Match_pseudoclass true ->
let = Parse_queue.consume_comments_and_ignore_whitespaces tokens in
let = fn_name_with_loc, comments
and fn_selectors_with_loc = consume_function_items_as_selectors tokens in
Pseudoclass_element_selector.Function_with_selectors
(fn_name_with_comments, fn_selectors_with_loc)
| _, _ ->
let fn_items_with_loc = consume_function_items_as_component_values tokens in
Function (fn_name_with_loc, fn_items_with_loc))
| token ->
Parse_queue.throw_error_for_token
~f:(fun token ->
[%string
"%{force error_msg} Expected an identifier or function but got %{token#Token}"])
token
and consume_pseudoclass_selector tokens =
let pseudoclass_selector = parse_pseudo_class_like_selector ~kind:`Pseudoclass tokens in
Selector.Pseudoclass pseudoclass_selector
and consume_pseudoelement_selector tokens =
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Is COLON)
~error_msg:(fun _ -> "Pseudoelement selector must start with a colon")
tokens;
let pseudoelement_selector =
parse_pseudo_class_like_selector ~kind:`Pseudoelement tokens
in
Selector.Pseudoelement pseudoelement_selector
and consume_subclass_selector tokens =
match Parse_queue.peek_token_exn tokens with
| HASH (id, flag) ->
Parse_queue.dequeue_and_ignore_exn tokens;
Selector.Id (Ident_like.to_string id, flag)
| DELIM "." ->
Parse_queue.dequeue_and_ignore_exn tokens;
let ident, _ =
Parse_queue.maybe_throw_ocaml_code_error tokens;
Parse_queue.require_next_token_to_match
~matches:(Is IDENT)
~error_msg:(fun token ->
[%string
"Error while parsing class. Expected a CSS identifier but got %{token#Token}"])
tokens
in
Class (Ident_like.to_string ident)
| LEFT_BRACKET ->
let block_contents =
Parse_queue.with_loc_exn
~f:(fun tokens ->
consume_block
~remove_surrounding_whitespaces:true
~allow_ocaml_code:false
~kind:`Bracket
tokens)
tokens
in
Selector.Attribute block_contents
| _ ->
Parse_queue.maybe_throw_ocaml_code_error tokens;
Parse_queue.dequeue_exn tokens
|> Parse_queue.throw_error_for_token ~f:(fun token ->
[%string
"Error while parsing class. Got unexpected token %{token#Token} at start of class"])
and consume_compound_selector tokens =
Parse_queue.with_loc_exn ~f:(consume_compound_selector_part ~stage:`Type) tokens
and tokens =
Parse_queue.fold_until
tokens
~init:()
~f:(fun () (token, _) ->
match token with
| COMMENT _ -> Continue ()
| DELIM ("~" | "+" | ">" | "|")
| WHITESPACE _
| RIGHT_PAREN
| COMMA
| LEFT_BRACE -> Stop true
| _ -> Stop false)
~finish:(fun () -> true)
and tokens =
match is_last_compound_selector_part_ignore_comments tokens with
| true -> []
| false -> Parse_queue.consume_comments_only tokens
(** [consume_compound_selector_part] ensures that we're parsing the compound selectors in
the proper order, as the selectors within a <compound-selector> have a schema that
they must adhere to.
If [strict] is false, we will __not__ check that the selectors follow a proper
ordering *)
and consume_compound_selector_part ~stage tokens =
let raise_error_from_token ~stage tokens =
Parse_queue.maybe_throw_ocaml_code_error tokens;
let stage_name =
match stage with
| `Type -> Some "type"
| `Subclass -> Some "subclass"
| `Pseudoelement -> Some "pseudoelement"
| `Unchecked -> None
in
Parse_queue.dequeue_exn tokens
|> Parse_queue.throw_error_for_token ~f:(fun token ->
Parse_queue.consume_and_ignore ~while_matches:(Not (Is EOF)) tokens;
let stage_name = Option.value ~default:"a" stage_name in
[%string
"Error while parsing selector. Expected start of %{stage_name} selector but got \
%{token#Token}"])
in
match Parse_queue.peek_token_exn tokens, stage with
| (
( DELIM ("~" | "+" | ">" | "|")
| WHITESPACE _
| RIGHT_PAREN
| COMMA
| LEFT_BRACE
| COMMENT _ )
, _ ) -> []
| DELIM "&", stage ->
let loc = Parse_queue.dequeue_exn tokens |> Location.from_token in
let = consume_comments_if_not_last_compound_selector_part tokens in
((Selector.Ampersand, loc), comment) :: consume_compound_selector_part ~stage tokens
| (IDENT _ | DELIM "*"), (`Type | `Unchecked) ->
let type_selector = Parse_queue.with_loc_exn ~f:consume_type_selector tokens in
let = consume_comments_if_not_last_compound_selector_part tokens in
(type_selector, comment) :: consume_compound_selector_part ~stage:`Subclass tokens
| (IDENT _ | DELIM "*"), _ ->
Parse_queue.dequeue_exn tokens
|> Parse_queue.throw_error_for_token ~f:(fun _ ->
"Error while parsing selector. Type selectors are only allowed at the start of a \
compound selector or directly after a leading ampersand")
| (DELIM "." | HASH _ | LEFT_BRACKET), (`Type | `Subclass | `Unchecked) ->
let subclass_selector =
Parse_queue.with_loc_exn ~f:consume_subclass_selector tokens
in
let = consume_comments_if_not_last_compound_selector_part tokens in
(subclass_selector, comment) :: consume_compound_selector_part ~stage:`Subclass tokens
| COLON, stage ->
(match Parse_queue.get_nth_token_exn ~n:1 tokens with
| COLON ->
let stage =
match stage with
| `Unchecked -> `Unchecked
| _ -> `Pseudoelement
in
let pseudoelement_selector =
Parse_queue.with_loc_exn ~f:consume_pseudoelement_selector tokens
in
let = consume_comments_if_not_last_compound_selector_part tokens in
(pseudoelement_selector, comment) :: consume_compound_selector_part ~stage tokens
| _ ->
let stage =
match stage with
| `Unchecked -> `Unchecked
| `Pseudoelement -> `Pseudoelement
| _ -> `Subclass
in
let pseudoclass_selector =
Parse_queue.with_loc_exn ~f:consume_pseudoclass_selector tokens
in
let = consume_comments_if_not_last_compound_selector_part tokens in
(pseudoclass_selector, comment) :: consume_compound_selector_part ~stage tokens)
| _, stage -> raise_error_from_token ~stage tokens
and consume_combinator tokens =
let combinator =
match
Parse_queue.dequeue_exn
~error_msg:(lazy "Hit unexpected EOF while parsing combinator")
tokens
with
| DELIM "~", _ -> Combinator.Subsequent_sibling
| DELIM "+", _ -> Next_sibling
| DELIM ">", _ -> Child
| DELIM "|", _ ->
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Equals (DELIM "|"))
~error_msg:(fun _ ->
[%string "Namespace separators are only valid for type selectors"])
tokens;
Combinator.Column
| WHITESPACE _, _ ->
Parse_queue.consume_and_ignore_whitespaces tokens;
(match is_start_of_combinator tokens with
| true -> consume_combinator tokens
| false -> Combinator.Descendant)
| token ->
Parse_queue.throw_error_for_token
~f:(fun token ->
[%string
"Error while parsing combinator. %{token#Token} is not a valid combinator"])
token
in
Parse_queue.consume_and_ignore_whitespaces tokens;
combinator
and is_start_of_combinator tokens =
match Parse_queue.peek_token_exn tokens with
| DELIM ("~" | "+" | ">" | "|") -> true
| _ -> false
and is_potentially_start_of_selector = function
| Token.DELIM ("&" | "*" | ".") | IDENT _ | COLON | HASH _ | LEFT_BRACKET -> true
| _ -> false
and is_next_token_potentially_start_of_selector tokens =
Parse_queue.peek_exn tokens |> fst |> is_potentially_start_of_selector
and consume_complex_selector_list
?(allow_relative = true)
~list_terminator
(tokens : Parse_queue.t)
: Complex_selector.t with_comments list
=
Parse_queue.process_into_list
~while_:(Not (Any [ Matches list_terminator; Is EOF ]))
~f:(fun _ ->
Parse_queue.consume_and_ignore_whitespaces tokens;
let maybe_leading_combinator =
match
( `Starts_combinator (is_start_of_combinator tokens)
, `Allow_relative allow_relative )
with
| `Starts_combinator true, `Allow_relative true ->
let combinator =
Complex_selector.Combinator
(Parse_queue.with_loc_exn ~f:consume_combinator tokens)
in
let = Parse_queue.consume_comments_and_ignore_whitespaces tokens in
Some (combinator, comment)
| `Starts_combinator true, `Allow_relative false ->
Parse_queue.dequeue_exn tokens
|> Parse_queue.throw_error_for_token ~f:(fun _ ->
"Relative selectors are not allowed here.")
| `Starts_combinator false, _ -> None
in
let potential_selectors_loc_for_error = Parse_queue.peek_exn tokens |> snd in
let selectors_with_loc =
Parse_queue.with_loc
~f:
(
Parse_queue.process_into_list
~while_:(Not (Any [ Matches list_terminator; Is EOF; Is COMMA ]))
~f:(fun _ ->
Parse_queue.consume_and_ignore_whitespaces tokens;
let current_selector = consume_compound_selector tokens in
let comments_and_whitespaces, =
Parse_queue.with_loc
~f:Parse_queue.consume_comment_and_whitespace
tokens
|> Option.value ~default:([], current_selector |> snd)
in
let , seen_whitespace =
List.fold
~init:(Reversed_list.[], false)
comments_and_whitespaces
~f:(fun (, seen_whitespace) -> function
| `Whitespace _ -> comments, true
| `Comment -> comment :: comments, seen_whitespace)
in
let = Reversed_list.rev comments in
let selector = Complex_selector.Selector current_selector, comments in
let combinator =
let is_descendant_combinator =
seen_whitespace && is_next_token_potentially_start_of_selector tokens
in
match
( `Starts_combinator (is_start_of_combinator tokens)
, `Is_descendant_combinator is_descendant_combinator )
with
| `Starts_combinator true, `Is_descendant_combinator false ->
let combinator =
Parse_queue.with_loc_exn ~f:consume_combinator tokens
in
let =
Parse_queue.consume_comments_and_ignore_whitespaces tokens
in
Parse_queue.throw_error_if_next_token_matches
~f:(Not (Matches is_potentially_start_of_selector))
~error_msg:"Combinators must be followed by a selector"
tokens;
Some (Complex_selector.Combinator combinator, comment)
| `Starts_combinator false, `Is_descendant_combinator true ->
let loc = comment_loc in
Some
( Combinator (Descendant, loc)
, []
)
| `Starts_combinator false, `Is_descendant_combinator false -> None
| `Starts_combinator true, `Is_descendant_combinator true ->
Parse_queue.raise
~loc:(Parse_queue.dequeue_exn tokens |> snd)
"Error parsing selector. Next token both starts a combinator and \
is a selector. This should never happen, please contact the \
maintainers of the CSS parser."
in
Some (List.filter_opt [ Some selector; combinator ])))
tokens
in
let has_comma = Parse_queue.dequeue_if_matches ~f:(Is COMMA) tokens in
match selectors_with_loc with
| None | Some ([], _) ->
Parse_queue.raise
~loc:potential_selectors_loc_for_error
"Expected a selector but nothing was found"
| Some (selectors, selector_loc) ->
let = Parse_queue.consume_comments_and_ignore_whitespaces tokens in
let selectors =
let selectors = List.concat selectors in
match maybe_leading_combinator with
| Some leading_combinator -> leading_combinator :: selectors
| None -> selectors
in
let is_next_token_end_of_list =
Parse_queue.peek_token_exn tokens |> list_terminator
in
(match has_comma && is_next_token_end_of_list with
| true ->
Parse_queue.raise
~loc:selector_loc
"The last selector in a list cannot have a dangling comma."
| false -> Some ((selectors, selector_loc), comments)))
tokens
and consume_qualified_rule tokens : Qualified_rule.t =
let prelude, prelude_loc =
let potential_prelude_error_loc = Parse_queue.peek_exn tokens |> snd in
let prelude_with_loc =
Parse_queue.with_loc
~f:
(consume_component_value_list
~allow_ocaml_code:false
~remove_surrounding_whitespaces:true
~while_:(Not (Any [ Is LEFT_BRACE; Is EOF ])))
tokens
in
let maybe_empty_prelude =
match prelude_with_loc with
| None -> None
| Some (prelude, prelude_loc) ->
let ignore_whitespace_and_comment = function
| Component_value.Whitespace _, _ | Comment _, _ -> false
| _ -> true
in
(match List.filter prelude ~f:ignore_whitespace_and_comment with
| [] -> None
| _ -> Some (prelude, prelude_loc))
in
match maybe_empty_prelude with
| None ->
Parse_queue.raise
~loc:potential_prelude_error_loc
"Qualified rule prelude cannot be empty."
| Some prelude_with_loc -> prelude_with_loc
in
let block, loc_2 = Parse_queue.with_loc_exn ~f:consume_declaration_list_block tokens in
let loc = Location.merge ~start:prelude_loc ~end_:loc_2 in
{ Qualified_rule.prelude = prelude, loc; block = block, loc_2; loc }
and remove_whitespace_from_end_of_component_values_list = function
| Reversed_list.((Component_value.Whitespace _, _) :: tl) ->
remove_whitespace_from_end_of_component_values_list tl
| component_values -> component_values
and process_important_from_declaration_value declaration_value =
let rec eat_whitespaces_and_comments component_values =
match remove_whitespace_from_end_of_component_values_list component_values with
| (Component_value.Comment (, ), ) :: tl ->
let , tl = eat_whitespaces_and_comments tl in
Reversed_list.((comment, comment_loc) :: child_comments), tl
| tl -> Reversed_list.[], tl
in
let component_values =
Reversed_list.of_list_rev declaration_value
|> remove_whitespace_from_end_of_component_values_list
in
let , tl = eat_whitespaces_and_comments component_values in
match tl with
| (Component_value.Ident (ident, _), _) :: tl
when String.lowercase ident |> String.equal "important" ->
let tl = remove_whitespace_from_end_of_component_values_list tl in
(match tl with
| (Component_value.Delim "!", _) :: tl ->
( remove_whitespace_from_end_of_component_values_list tl |> Reversed_list.rev
, (true, Reversed_list.rev end_comments) )
| _ -> Reversed_list.rev component_values, (false, []))
| _ -> Reversed_list.rev component_values, (false, [])
and consume_declaration ~ambiguity tokens =
let name, name_loc =
Parse_queue.require_next_token_to_match
~matches:(Is IDENT)
~error_msg:(fun _ -> "Declaration must start with a valid CSS identifier.")
tokens
and
=
Parse_queue.consume_comments_and_ignore_whitespaces tokens
in
let name = Ident_like.to_string name in
let is_custom_property =
String.is_prefix ~prefix:"--" name && String.length name > 2
in
let context =
let decl = Context.Declaration { property_name = name } in
match ambiguity with
| `Definite ->
decl
| `Maybe_selector ->
Ambiguous [ decl; Rules ]
in
let (), colon_loc =
Parse_queue.with_context
context
~f:(fun tokens ->
Parse_queue.require_next_token_to_match
~matches:(Is COLON)
~error_msg:(fun _ -> "Declaration name must be followed by a colon.")
tokens)
tokens
in
let check_maybe_missing_semicolon =
let seen_so_far = ref `Nothing in
let previous_token_loc = ref colon_loc in
let non_whitespace_component_value_before_ident_loc = ref None in
fun token (_component_value, component_value_loc) ->
let new_value =
match !seen_so_far, token with
| (`Nothing | `Ident), Token.IDENT _ ->
non_whitespace_component_value_before_ident_loc := Some !previous_token_loc;
`Ident
| `Ident, Token.(WHITESPACE _ | COMMENT _) -> `Ident
| `Ident, Token.COLON ->
let loc_end =
Option.value
~default:!previous_token_loc
!non_whitespace_component_value_before_ident_loc
in
Parse_queue.consume_and_ignore ~while_matches:(Not (Is EOF)) tokens;
Parse_queue.raise
~loc:(Location.of_positions ~start:name_loc.loc_start ~end_:loc_end.loc_end)
"Declaration is missing a semicolon"
| _ ->
non_whitespace_component_value_before_ident_loc := None;
`Nothing
in
(match token with
| Token.WHITESPACE _ -> ()
| _ -> previous_token_loc := component_value_loc);
seen_so_far := new_value
in
let declaration_value_with_loc =
let maybe_declaration_value_list =
Parse_queue.with_loc
~context:(Some context)
~f:
(consume_component_value_list
~maybe_throw_error:check_maybe_missing_semicolon
~remove_surrounding_whitespaces:true
~allow_ocaml_code:true
~while_:(Not (Any [ Is SEMICOLON; Is EOF; Is RIGHT_BRACE ])))
tokens
in
match maybe_declaration_value_list with
| None ->
let loc_end = Parse_queue.peek_exn tokens |> snd in
let loc =
Location.of_positions ~start:colon_loc.loc_start ~end_:loc_end.loc_start
in
[], loc
| Some value -> value
in
if
Parse_queue.dequeue_and_check_if_next_token_matches
~matches:(Not (Is SEMICOLON))
tokens
then (
let declaration_value_loc =
fst declaration_value_with_loc
|> List.last
|> Option.value_map ~f:snd ~default:(snd declaration_value_with_loc)
in
let loc = Location.merge ~start:name_loc ~end_:declaration_value_loc in
Parse_queue.handle_recoverable_error
tokens
(Missing_semicolon_at_end_of_declaration_list { loc }));
match declaration_value_with_loc with
| [], loc when not is_custom_property ->
ignore
@@ Parse_queue.with_context
~f:(fun tokens -> Parse_queue.dequeue tokens)
context
tokens;
Parse_queue.raise ~loc "Declaration value cannot be empty"
| declaration_value, declaration_value_loc ->
let component_values, is_important =
process_important_from_declaration_value declaration_value
in
let is_empty_declaration =
List.fold_until
declaration_value
~init:()
~f:(fun () -> function
| Component_value.Whitespace _, _ | Component_value.Comment _, _ -> Continue ()
| _ -> Stop false)
~finish:(fun () -> true)
in
(match (not is_custom_property) && is_empty_declaration with
| true ->
Parse_queue.raise ~loc:declaration_value_loc "Declaration value cannot be empty"
| false ->
{ Declaration.name = (name, name_loc), name_comments
; value = component_values, declaration_value_loc
; important = is_important
})
and consume_at_rule tokens : At_rule.t =
let at_rule_name, at_token_loc =
Parse_queue.require_next_token_to_match
~matches:(Is AT_KEYWORD)
~error_msg:(fun token ->
[%string "Expected '@<identifier>' but got %{token#Token}"])
tokens
in
let at_rule_name = Ident_like.to_string at_rule_name in
let prelude_with_loc =
let%bind.Option prelude, loc =
Parse_queue.with_loc
~f:
(consume_component_value_list
~allow_ocaml_code:false
~remove_surrounding_whitespaces:true
~while_:(Not (Any [ Is EOF; Is LEFT_BRACE; Is SEMICOLON ])))
tokens
in
match prelude with
| [] -> None
| prelude -> Some (prelude, loc)
in
let block, block_loc =
match Parse_queue.peek tokens with
| Some (Token.SEMICOLON, _) ->
let semicolon_token = Parse_queue.dequeue_exn tokens in
None, Location.from_token semicolon_token
| Some (Token.LEFT_BRACE, _) ->
(match String.lowercase at_rule_name with
| "layer" | "media" | "supports" | "when" | "else" | "container" ->
let block, block_loc = Parse_queue.with_loc_exn ~f:consume_style_block tokens in
Some (At_rule.Style_block (block, block_loc)), block_loc
| _ ->
let block, loc =
Parse_queue.with_loc_exn ~f:consume_declaration_list_block tokens
in
Some (At_rule.Declaration_list (block, loc)), loc)
| None ->
Parse_queue.raise
~loc:at_token_loc
"Unexpected end of file while parsing at-rule. Please contact the maintainers of \
the CSS parser."
| Some token ->
Parse_queue.throw_error_for_token token ~f:(fun token ->
[%string
"Error while parsing at-rule. Expected a semicolon or start of block but got \
%{token#Token}"])
in
let loc = Location.merge ~start:at_token_loc ~end_:block_loc in
{ At_rule.name = at_rule_name; prelude = prelude_with_loc; block; loc }
and consume_declaration_list tokens ~while_ : Declaration_list.Element.t list =
Parse_queue.with_context
Block
~f:(fun tokens ->
Parse_queue.process_into_list tokens ~while_ ~f:(function
| Token.WHITESPACE _ | SEMICOLON -> None
| COMMENT ->
Some
(Declaration_list.Element.Comment
(comment, Parse_queue.dequeue_exn tokens |> Location.from_token))
| AT_KEYWORD _ ->
let at_rule = (Parse_queue.with_loc_exn ~f:consume_at_rule) tokens in
Some (At_rule at_rule)
| _ ->
(match is_declaration_or_qualified_rule tokens with
| `Declaration ambiguity ->
let decl =
Parse_queue.with_loc_exn ~f:(consume_declaration ~ambiguity) tokens
in
Some (Declaration decl)
| `Qualified_rule ->
let rule = Parse_queue.with_loc_exn ~f:consume_qualified_rule tokens in
Some (Qualified_rule rule))))
tokens
and consume_declaration_list_block tokens : Declaration_list.Element.t list =
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Is LEFT_BRACE)
~error_msg:(fun _ -> "Declaration list block must start with an opening left brace")
tokens;
let declarations =
consume_declaration_list ~while_:(Not (Any [ Is RIGHT_BRACE; Is EOF ])) tokens
in
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Is RIGHT_BRACE)
~error_msg:(fun _ -> "Missing closing right brace for declaration list block.")
tokens;
declarations
and consume_block
~remove_surrounding_whitespaces
~allow_ocaml_code
~kind
tokens
=
let match_start_of_block, match_end_of_block, kind_string =
match kind with
| `Brace -> Token.is_left_brace, Token.is_right_brace, "brace"
| `Paren -> Token.is_left_paren, Token.is_right_paren, "paren"
| `Bracket -> Token.is_left_bracket, Token.is_right_bracket, "bracket"
in
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Matches match_start_of_block)
~error_msg:(fun _ -> [%string "Block must start with an opening left %{kind_string}"])
tokens;
let block_items =
consume_component_value_list
tokens
~remove_surrounding_whitespaces
~allow_ocaml_code
~while_:(Not (Any [ Is EOF; Matches match_end_of_block ]))
in
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Matches match_end_of_block)
~error_msg:(fun _ -> [%string "Block must end with a closing right %{kind_string}"])
tokens;
block_items
and consume_component_value_list
: remove_surrounding_whitespaces:bool -> allow_ocaml_code:bool
->
?maybe_throw_error:(Token.t -> Component_value.t with_loc -> unit)
-> while_:Parse_queue.Match.t -> Parse_queue.t -> Component_value.t with_loc list
=
fun ~remove_surrounding_whitespaces
~allow_ocaml_code
?(maybe_throw_error = fun _ _ -> ())
~(while_ : Parse_queue.Match.t)
tokens ->
if remove_surrounding_whitespaces then Parse_queue.consume_and_ignore_whitespaces tokens;
let items = ref Reversed_list.[] in
Parse_queue.process
~while_
~f:(fun token ->
let component_value =
consume_component_value ~remove_surrounding_whitespaces ~allow_ocaml_code tokens
in
items := component_value :: !items;
maybe_throw_error token component_value)
tokens;
let items =
match remove_surrounding_whitespaces with
| true -> remove_whitespace_from_end_of_component_values_list !items
| false -> !items
in
Reversed_list.rev items
and consume_block_as_component_value
~remove_surrounding_whitespaces
~allow_ocaml_code
~kind
tokens
=
let block_items, loc =
Parse_queue.with_loc_exn
~f:(consume_block ~remove_surrounding_whitespaces ~allow_ocaml_code ~kind)
tokens
in
match kind with
| `Brace -> Component_value.Brace_block block_items, loc
| `Paren -> Paren_block block_items, loc
| `Bracket -> Bracket_block block_items, loc
and consume_function_items_as_component_values ?(allow_ocaml_code = false) tokens =
let items =
consume_component_value_list
~remove_surrounding_whitespaces:true
~allow_ocaml_code
~while_:(Not (Any [ Is EOF; Is RIGHT_PAREN ]))
tokens
in
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Is RIGHT_PAREN)
~error_msg:(fun token ->
[%string
"Error while parsing function. Expected closing paren but got %{token#Token}"])
tokens;
items
and consume_function_items_as_selectors tokens =
let function_items, function_items_loc =
Parse_queue.with_loc_exn
~f:
(consume_complex_selector_list
~list_terminator:Token.is_right_paren
~allow_relative:true)
tokens
in
Parse_queue.require_next_token_to_match_and_ignore
~matches:(Is RIGHT_PAREN)
~error_msg:(fun token ->
[%string
"Error while parsing function. Expected closing paren but got %{token#Token}"])
tokens;
function_items, function_items_loc
and consume_component_value
~remove_surrounding_whitespaces
?(allow_ocaml_code = false)
tokens
=
let potentially_function_or_block =
match Parse_queue.peek_token_exn tokens with
| FUNCTION fn_name ->
let loc = Parse_queue.dequeue_exn tokens |> Location.from_token in
let function_items, function_items_loc =
Parse_queue.with_loc_exn
~f:(consume_function_items_as_component_values ~allow_ocaml_code)
tokens
in
let fn_name = Ident_like.to_string fn_name in
( Component_value.Function ((fn_name, loc), function_items)
, Location.merge ~start:loc ~end_:function_items_loc )
|> Option.return
| LEFT_BRACE ->
consume_block_as_component_value
~remove_surrounding_whitespaces
~allow_ocaml_code
~kind:`Brace
tokens
|> Option.return
| LEFT_PAREN ->
consume_block_as_component_value
~remove_surrounding_whitespaces
~allow_ocaml_code
~kind:`Paren
tokens
|> Option.return
| LEFT_BRACKET ->
consume_block_as_component_value
~remove_surrounding_whitespaces
~allow_ocaml_code
~kind:`Bracket
tokens
|> Option.return
| _ -> None
in
match potentially_function_or_block with
| Some fn_or_block -> fn_or_block
| None ->
if not allow_ocaml_code then Parse_queue.maybe_throw_ocaml_code_error tokens;
let token, token_loc =
let token, _ = Parse_queue.peek_exn tokens in
match token with
| OCAML_CODE _ ->
Parse_queue.with_context
Interpolation
~f:(fun tokens -> Parse_queue.dequeue_exn tokens)
tokens
| _ -> Parse_queue.dequeue_exn tokens
in
let component_value =
match token with
| Token.WHITESPACE value -> Component_value.Whitespace value
| STRING str -> String str
| IDENT ident -> Ident (Ident_like.to_string ident, token_loc)
| PERCENTAGE p -> Percentage p
| URL url -> Url url
| DELIM d -> Delim d
| COMMENT c -> Comment (c, token_loc)
| OCAML_CODE c -> Ocaml_code (c, token_loc)
| HASH (h, flag) -> Hash (Ident_like.to_string h, flag)
| NUMBER n -> Number n
| DIMENSION (number, num_type, exponent, dimension) ->
Dimension (number, num_type, exponent, Ident_like.to_string dimension)
| COLON -> Colon
| CDO -> Cdo
| CDC -> Cdc
| COMMA -> Comma
| SEMICOLON -> Semicolon
| RIGHT_BRACKET -> Right_bracket
| RIGHT_BRACE -> Right_brace
| RIGHT_PAREN -> Right_paren
| BAD_STRING str -> Bad_string str
| BAD_URL url -> Bad_string url
| AT_KEYWORD name -> At_keyword (Ident_like.to_string name)
| token ->
let loc = Parse_queue.dequeue_exn tokens |> Location.from_token in
Parse_queue.throw_error_for_token (token, loc) ~f:(fun token ->
[%string
"Encountered unexpected token %{token#Token} when parsing component value"])
in
component_value, token_loc
;;
let stylesheet ~(parsing_config : Parsing_config.t) tokens =
let tokens = Parse_queue.of_list ~parsing_config tokens in
consume_list_of_rules tokens
;;
let style_block_contents ~(parsing_config : Parsing_config.t) tokens =
let tokens = Parse_queue.of_list ~parsing_config tokens in
match
Parse_queue.with_loc
~f:(fun tokens -> consume_style_block_contents ~while_:(Not (Is EOF)) tokens)
tokens
with
| None ->
let _, loc =
Parse_queue.require_next_token_to_match
~error_msg:(fun _ ->
"No EOF token found when consuming empty style block declaration. This is a \
parser error, please contact the maintainers of the CSS parser")
~matches:(Is EOF)
tokens
in
[], loc
| Some style_block_contents -> style_block_contents
;;
let for_apply_style tokens =
let tokens =
Parse_queue.of_list ~parsing_config:Parsing_config.ignore_recoverable_errors tokens
in
match
Parse_queue.with_loc
~f:
(consume_component_value_list
~remove_surrounding_whitespaces:false
~allow_ocaml_code:true
~while_:(Not (Is EOF)))
tokens
with
| None ->
let _, loc =
Parse_queue.require_next_token_to_match
~error_msg:(fun _ ->
"No EOF token found empty CSS string. This is a parser error, please contact \
the maintainers of the CSS parser")
~matches:(Is EOF)
tokens
in
[], loc
| Some apply_style_sheet -> apply_style_sheet
;;