File: CSSPropertyParserConsumer%2BImage.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (1310 lines) | stat: -rw-r--r-- 54,772 bytes parent folder | download | duplicates (7)
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
/*
 * Copyright (C) 2024 Samuel Weinig <sam@webkit.org>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "CSSPropertyParserConsumer+Image.h"

#include "CSSCalcSymbolTable.h"
#include "CSSCanvasValue.h"
#include "CSSColor.h"
#include "CSSCrossfadeValue.h"
#include "CSSCursorImageValue.h"
#include "CSSFilterImageValue.h"
#include "CSSGradientValue.h"
#include "CSSImageSetOptionValue.h"
#include "CSSImageSetValue.h"
#include "CSSImageValue.h"
#include "CSSNamedImageValue.h"
#include "CSSPaintImageValue.h"
#include "CSSParserContext.h"
#include "CSSParserTokenRange.h"
#include "CSSPrimitiveNumericTypes.h"
#include "CSSPropertyParserConsumer+AngleDefinitions.h"
#include "CSSPropertyParserConsumer+AnglePercentageDefinitions.h"
#include "CSSPropertyParserConsumer+CSSPrimitiveValueResolver.h"
#include "CSSPropertyParserConsumer+Color.h"
#include "CSSPropertyParserConsumer+ColorInterpolationMethod.h"
#include "CSSPropertyParserConsumer+Filter.h"
#include "CSSPropertyParserConsumer+Ident.h"
#include "CSSPropertyParserConsumer+LengthDefinitions.h"
#include "CSSPropertyParserConsumer+LengthPercentageDefinitions.h"
#include "CSSPropertyParserConsumer+MetaConsumer.h"
#include "CSSPropertyParserConsumer+MetaResolver.h"
#include "CSSPropertyParserConsumer+Number.h"
#include "CSSPropertyParserConsumer+NumberDefinitions.h"
#include "CSSPropertyParserConsumer+Percentage.h"
#include "CSSPropertyParserConsumer+PercentageDefinitions.h"
#include "CSSPropertyParserConsumer+Position.h"
#include "CSSPropertyParserConsumer+Primitives.h"
#include "CSSPropertyParserConsumer+ResolutionDefinitions.h"
#include "CSSPropertyParserConsumer+String.h"
#include "CSSPropertyParserConsumer+URL.h"
#include "CSSPropertyParserOptions.h"
#include "CSSValue.h"
#include "CSSValueList.h"
#include "CSSValuePool.h"
#include "CSSVariableData.h"
#include "StyleImage.h"
#include <wtf/SortedArrayMap.h>

namespace WebCore {
namespace CSSPropertyParserHelpers {

// Used by radial gradient consumers internally.
enum class ShapeKeyword : bool { Circle, Ellipse };

// MARK: Deprecated <gradient> values

template<CSSValueID zeroValue, CSSValueID oneHundredValue> static std::optional<CSS::NumberOrPercentage<>> consumeDeprecatedGradientPositionComponent(CSSParserTokenRange& range, const CSSParserContext& context)
{
    if (range.peek().type() == IdentToken) {
        if (consumeIdent<zeroValue>(range))
            return CSS::NumberOrPercentage<> { CSS::PercentageRaw<> { 0 } };
        if (consumeIdent<oneHundredValue>(range))
            return CSS::NumberOrPercentage<> { CSS::PercentageRaw<> { 100 } };
        if (consumeIdent<CSSValueCenter>(range))
            return CSS::NumberOrPercentage<> { CSS::PercentageRaw<> { 50 } };
        return std::nullopt;
    }
    return MetaConsumer<CSS::Number<>, CSS::Percentage<>>::consume(range, context, { }, { });
}

static std::optional<CSS::DeprecatedGradientPosition> consumeDeprecatedGradientPosition(CSSParserTokenRange& range, const CSSParserContext& context)
{
    auto horizontal = consumeDeprecatedGradientPositionComponent<CSSValueLeft, CSSValueRight>(range, context);
    if (!horizontal)
        return std::nullopt;

    auto vertical = consumeDeprecatedGradientPositionComponent<CSSValueTop, CSSValueBottom>(range, context);
    if (!vertical)
        return std::nullopt;

    return { { WTFMove(*horizontal), WTFMove(*vertical) } };
}

static std::optional<CSS::Color> consumeDeprecatedGradientStopColor(CSSParserTokenRange& range, const CSSParserContext& context)
{
    if (range.peek().id() == CSSValueCurrentcolor)
        return std::nullopt;
    return consumeUnresolvedColor(range, context);
}

static std::optional<CSS::GradientDeprecatedColorStop> consumeDeprecatedGradientColorStop(CSSParserTokenRange& range, const CSSParserContext& context)
{
    auto id = range.peek().functionId();
    switch (id) {
    case CSSValueFrom:
    case CSSValueTo:
    case CSSValueColorStop:
        break;

    default:
        return std::nullopt;
    }

    auto args = consumeFunction(range);
    std::optional<CSS::GradientDeprecatedColorStopPosition> position;
    switch (id) {
    case CSSValueFrom:
        position = CSS::NumberRaw<> { 0 };
        break;
    case CSSValueTo:
        position = CSS::NumberRaw<> { 1 };
        break;
    case CSSValueColorStop: {
        auto numberOrPercentage = MetaConsumer<CSS::Number<>, CSS::Percentage<>>::consume(args, context, { }, { });
        if (!numberOrPercentage)
            return std::nullopt;
        if (!consumeCommaIncludingWhitespace(args))
            return std::nullopt;
        position = WTFMove(*numberOrPercentage);
        break;
    }
    default:
        ASSERT_NOT_REACHED();
        return std::nullopt;
    }

    auto color = consumeDeprecatedGradientStopColor(args, context);
    if (!color || !args.atEnd())
        return std::nullopt;

    return CSS::GradientDeprecatedColorStop {
        .color = WTFMove(*color),
        .position = WTFMove(*position)
    };
}

static std::optional<CSS::GradientDeprecatedColorStopList> consumeDeprecatedGradientColorStops(CSSParserTokenRange& range, const CSSParserContext& context)
{
    CSS::GradientDeprecatedColorStopList::Vector stops;
    while (consumeCommaIncludingWhitespace(range)) {
        auto stop = consumeDeprecatedGradientColorStop(range, context);
        if (!stop)
            return std::nullopt;
        stops.append(WTFMove(*stop));
    }
    stops.shrinkToFit();

    return { { WTFMove(stops) } };
}

static RefPtr<CSSValue> consumeDeprecatedLinearGradient(CSSParserTokenRange& range, const CSSParserContext& context)
{
    if (!consumeCommaIncludingWhitespace(range))
        return nullptr;

    auto first = consumeDeprecatedGradientPosition(range, context);
    if (!first)
        return nullptr;

    if (!consumeCommaIncludingWhitespace(range))
        return nullptr;

    auto second = consumeDeprecatedGradientPosition(range, context);
    if (!second)
        return nullptr;

    auto stops = consumeDeprecatedGradientColorStops(range, context);
    if (!stops)
        return nullptr;

    return CSSGradientValue::create(
        FunctionNotation<CSSValueWebkitGradient, CSS::DeprecatedLinearGradient> {
            .parameters = {
                .colorInterpolationMethod = CSS::GradientColorInterpolationMethod::legacyMethod(AlphaPremultiplication::Premultiplied),
                .gradientLine = { WTFMove(*first), WTFMove(*second) },
                .stops = WTFMove(*stops)
            }
        }
    );
}

static RefPtr<CSSValue> consumeDeprecatedRadialGradient(CSSParserTokenRange& range, const CSSParserContext& context)
{
    if (!consumeCommaIncludingWhitespace(range))
        return nullptr;

    auto first = consumeDeprecatedGradientPosition(range, context);
    if (!first)
        return nullptr;

    if (!consumeCommaIncludingWhitespace(range))
        return nullptr;

    auto firstRadius = MetaConsumer<CSS::Number<CSS::Nonnegative>>::consume(range, context, { }, { });
    if (!firstRadius)
        return nullptr;

    if (!consumeCommaIncludingWhitespace(range))
        return nullptr;

    auto second = consumeDeprecatedGradientPosition(range, context);
    if (!second)
        return nullptr;

    if (!consumeCommaIncludingWhitespace(range))
        return nullptr;

    auto secondRadius = MetaConsumer<CSS::Number<CSS::Nonnegative>>::consume(range, context, { }, { });
    if (!secondRadius)
        return nullptr;

    auto stops = consumeDeprecatedGradientColorStops(range, context);
    if (!stops)
        return nullptr;

    return CSSGradientValue::create(
        FunctionNotation<CSSValueWebkitGradient, CSS::DeprecatedRadialGradient> {
            .parameters = {
                .colorInterpolationMethod = CSS::GradientColorInterpolationMethod::legacyMethod(AlphaPremultiplication::Premultiplied),
                .gradientBox = {
                    .first = WTFMove(*first),
                    .firstRadius = WTFMove(*firstRadius),
                    .second = WTFMove(*second),
                    .secondRadius = WTFMove(*secondRadius),
                },
                .stops = WTFMove(*stops)
            }
        }
    );
}

static RefPtr<CSSValue> consumeDeprecatedGradient(CSSParserTokenRange& range, const CSSParserContext& context)
{
    switch (range.consumeIncludingWhitespace().id()) {
    case CSSValueLinear:
        return consumeDeprecatedLinearGradient(range, context);
    case CSSValueRadial:
        return consumeDeprecatedRadialGradient(range, context);
    default:
        return nullptr;
    }
}

// MARK: <color-stop-list> | <angular-color-stop-list>
// https://drafts.csswg.org/css-images-4/#typedef-color-stop-list

enum class SupportsColorHints : bool { No, Yes };

static std::optional<CSS::Color> consumeStopColor(CSSParserTokenRange& range, const CSSParserContext& context)
{
    return consumeUnresolvedColor(range, context);
}

template<SupportsColorHints supportsColorHints, typename Stop, typename Consumer> static std::optional<CSS::GradientColorStopList<Stop>> consumeColorStopList(CSSParserTokenRange& range, const CSSParserContext& context, Consumer&& consumeStopPosition)
{
    typename CSS::GradientColorStopList<Stop>::Vector stops;

    // The first color stop cannot be a color hint.
    bool previousStopWasColorHint = true;
    do {
        Stop stop { consumeStopColor(range, context), consumeStopPosition(range) };
        if (!stop.color && !stop.position)
            return std::nullopt;

        // Two color hints in a row are not allowed.
        if (!stop.color && (supportsColorHints == SupportsColorHints::No || previousStopWasColorHint))
            return std::nullopt;
        previousStopWasColorHint = !stop.color;

        // Stops with both a color and a position can have a second position, which shares the same color.
        if (stop.color && stop.position) {
            if (auto secondPosition = consumeStopPosition(range)) {
                stops.append(stop);
                stop.position = WTFMove(secondPosition);
            }
        }
        stops.append(WTFMove(stop));
    } while (consumeCommaIncludingWhitespace(range));

    // The last color stop cannot be a color hint.
    if (previousStopWasColorHint)
        return std::nullopt;

    // Must have at least one stop to be valid.
    if (stops.isEmpty())
        return std::nullopt;

    stops.shrinkToFit();

    return { WTFMove(stops) };
}

template<SupportsColorHints supportsColorHints> static std::optional<CSS::GradientLinearColorStopList> consumeLinearColorStopList(CSSParserTokenRange& range, const CSSParserContext& context)
{
    const auto options = CSSPropertyParserOptions {
        .parserMode = context.mode,
        .unitless = UnitlessQuirk::Forbid,
        .unitlessZero = UnitlessZeroQuirk::Allow
    };

    return consumeColorStopList<supportsColorHints, CSS::GradientLinearColorStop>(range, context, [&](auto& range) {
        return MetaConsumer<CSS::LengthPercentage<>>::consume(range, context, { }, options);
    });
}

template<SupportsColorHints supportsColorHints> static std::optional<CSS::GradientAngularColorStopList> consumeAngularColorStopList(CSSParserTokenRange& range, const CSSParserContext& context)
{
    const auto options = CSSPropertyParserOptions {
        .parserMode = context.mode,
        .unitless = UnitlessQuirk::Forbid,
        .unitlessZero = UnitlessZeroQuirk::Allow
    };

    return consumeColorStopList<supportsColorHints, CSS::GradientAngularColorStop>(range, context, [&](auto& range) {
        return MetaConsumer<CSS::AnglePercentage<>>::consume(range, context, { }, options);
    });
}

static bool stopColorIs8Bit(const CSS::Color& color)
{
    return color.isKeyword() || color.absoluteColor().tryGetAsSRGBABytes();
}

static bool stopColorIs8Bit(const Markable<CSS::Color>& color)
{
    return !color || stopColorIs8Bit(*color);
}

template<typename Stop> static CSS::GradientColorInterpolationMethod computeGradientColorInterpolationMethod(std::optional<ColorInterpolationMethod> parsedColorInterpolationMethod, const CSS::GradientColorStopList<Stop>& stops)
{
    // We detect whether stops use legacy vs. non-legacy CSS color syntax using the following rules:
    //  - A CSSValueID is always considered legacy since all keyword based colors are considered legacy by the spec.
    //  - An actual Color value is considered legacy if it is stored as 8-bit sRGB.
    //
    // While this is accurate now, we should consider a more robust mechanism to detect this at parse
    // time, perhaps keeping this information in the CSSPrimitiveValue itself.

    auto defaultColorInterpolationMethod = CSS::GradientColorInterpolationMethod::Default::SRGB;
    for (auto& stop : stops) {
        if (stopColorIs8Bit(stop.color))
            continue;

        defaultColorInterpolationMethod = CSS::GradientColorInterpolationMethod::Default::OKLab;
        break;
    }

    if (parsedColorInterpolationMethod)
        return { *parsedColorInterpolationMethod, defaultColorInterpolationMethod };

    switch (defaultColorInterpolationMethod) {
    case CSS::GradientColorInterpolationMethod::Default::SRGB:
        return { { ColorInterpolationMethod::SRGB { }, AlphaPremultiplication::Premultiplied }, defaultColorInterpolationMethod };

    case CSS::GradientColorInterpolationMethod::Default::OKLab:
        return { { ColorInterpolationMethod::OKLab { }, AlphaPremultiplication::Premultiplied }, defaultColorInterpolationMethod };
    }

    ASSERT_NOT_REACHED();
    return { { ColorInterpolationMethod::SRGB { }, AlphaPremultiplication::Premultiplied }, defaultColorInterpolationMethod };
}

// MARK: Compat <gradient> values
// https://compat.spec.whatwg.org/#css-gradient-fns

// MARK: <-webkit-linear-gradient()> | <-webkit-repeating-linear-gradient()>
// https://compat.spec.whatwg.org/#css-gradients-webkit-linear-gradient

template<CSSValueID Name> static RefPtr<CSSValue> consumePrefixedLinearGradient(CSSParserTokenRange& range, const CSSParserContext& context)
{
    // https://compat.spec.whatwg.org/#css-gradients-webkit-linear-gradient/ states that -webkit-linear-gradient() and
    // -webkit-repeating-linear-gradient() must be "treated as an alias of linear-gradient as defined in [css3-images-20110217]."
    // In [css3-images-20110217] the grammar was defined as:
    //
    //   <linear-gradient> = linear-gradient([ [ [top | bottom] || [left | right] ] | <angle> ,]? <color-stop>[, <color-stop>]+);
    //
    // see https://www.w3.org/TR/2011/WD-css3-images-20110217/#linear-gradients.

    static constexpr std::pair<CSSValueID, CSS::Vertical> verticalMappings[] {
        { CSSValueTop, CSS::Vertical { CSS::Keyword::Top { } } },
        { CSSValueBottom, CSS::Vertical { CSS::Keyword::Bottom { } } },
    };
    static constexpr SortedArrayMap verticalMap { verticalMappings };

    static constexpr std::pair<CSSValueID, CSS::Horizontal> horizontalMappings[] {
        { CSSValueLeft, CSS::Horizontal { CSS::Keyword::Left { } } },
        { CSSValueRight, CSS::Horizontal { CSS::Keyword::Right { } } },
    };
    static constexpr SortedArrayMap horizontalMap { horizontalMappings };

    auto consumeKeywordGradientLineKnownHorizontal = [&](CSSParserTokenRange& range, CSS::Horizontal knownHorizontal) -> CSS::PrefixedLinearGradient::GradientLine {
        if (auto vertical = consumeIdentUsingMapping(range, verticalMap))
            return SpaceSeparatedTuple { knownHorizontal, *vertical };
        return knownHorizontal;
    };

    auto consumeKeywordGradientLineKnownVertical = [&](CSSParserTokenRange& range, CSS::Vertical knownVertical) -> CSS::PrefixedLinearGradient::GradientLine {
        if (auto horizontal = consumeIdentUsingMapping(range, horizontalMap))
            return SpaceSeparatedTuple { *horizontal, knownVertical };
        return knownVertical;
    };

    auto consumeKeywordGradientLine = [&](CSSParserTokenRange& range) -> std::optional<CSS::PrefixedLinearGradient::GradientLine> {
        switch (range.peek().id()) {
        case CSSValueLeft:
            range.consumeIncludingWhitespace();
            return consumeKeywordGradientLineKnownHorizontal(range, CSS::Horizontal { CSS::Keyword::Left { } });
        case CSSValueRight:
            range.consumeIncludingWhitespace();
            return consumeKeywordGradientLineKnownHorizontal(range, CSS::Horizontal { CSS::Keyword::Right { } });
        case CSSValueTop:
            range.consumeIncludingWhitespace();
            return consumeKeywordGradientLineKnownVertical(range, CSS::Vertical { CSS::Keyword::Top { } });
        case CSSValueBottom:
            range.consumeIncludingWhitespace();
            return consumeKeywordGradientLineKnownVertical(range, CSS::Vertical { CSS::Keyword::Bottom { } });
        default:
            return { };
        }
    };

    std::optional<CSS::PrefixedLinearGradient::GradientLine> gradientLine;

    const auto angleConsumeOptions = CSSPropertyParserOptions {
        .parserMode = context.mode,
        .unitless = UnitlessQuirk::Forbid,
        .unitlessZero = UnitlessZeroQuirk::Allow
    };

    if (auto angle = MetaConsumer<CSS::Angle<>>::consume(range, context, { }, angleConsumeOptions)) {
        gradientLine = WTF::switchOn(WTFMove(*angle), [](auto&& value) -> CSS::PrefixedLinearGradient::GradientLine { return value; });
        if (!consumeCommaIncludingWhitespace(range))
            return nullptr;
    } else if (auto keywordGradientLine = consumeKeywordGradientLine(range)) {
        gradientLine = WTFMove(*keywordGradientLine);
        if (!consumeCommaIncludingWhitespace(range))
            return nullptr;
    }

    auto stops = consumeLinearColorStopList<SupportsColorHints::No>(range, context);
    if (!stops)
        return nullptr;

    return CSSGradientValue::create(
        FunctionNotation<Name, CSS::PrefixedLinearGradient> {
            .parameters = {
                .colorInterpolationMethod = CSS::GradientColorInterpolationMethod::legacyMethod(AlphaPremultiplication::Premultiplied),
                .gradientLine = gradientLine.value_or(CSS::Vertical { CSS::Keyword::Top { } }),
                .stops = WTFMove(*stops)
            }
        }
    );
}

// MARK: <-webkit-radial-gradient()> | <-webkit-repeating-radial-gradient()>
// https://compat.spec.whatwg.org/#css-gradients-webkit-radial-gradient

template<CSSValueID Name> static RefPtr<CSSValue> consumePrefixedRadialGradient(CSSParserTokenRange& range, const CSSParserContext& context)
{
    // https://compat.spec.whatwg.org/#css-gradients-webkit-radial-gradient/ states that -webkit-radial-gradient() and
    // -webkit-repeating-radial-gradient() must be "treated as an alias of radial-gradient as defined in [css3-images-20110217]."
    // In [css3-images-20110217] the grammar was defined as:
    //
    //   <radial-gradient> = radial-gradient([<bg-position>,]? [ [<shape> || <size>] | [<length> | <percentage>]{2} ,]? <color-stop>[, <color-stop>]+);
    //   <shape> = [ circle | ellipse ]
    //   <size> = [ closest-side | closest-corner | farthest-side | farthest-corner | contain | cover ]
    //
    //      defaults to ‘ellipse cover’.
    //
    // see https://www.w3.org/TR/2011/WD-css3-images-20110217/#radial-gradients.

    static constexpr std::pair<CSSValueID, ShapeKeyword> shapeMappings[] {
        { CSSValueCircle, ShapeKeyword::Circle },
        { CSSValueEllipse, ShapeKeyword::Ellipse },
    };
    static constexpr SortedArrayMap shapeMap { shapeMappings };

    static constexpr std::pair<CSSValueID, CSS::PrefixedRadialGradient::Extent> extentMappings[] {
        { CSSValueContain, CSS::PrefixedRadialGradient::Extent { CSS::Keyword::Contain { } } },
        { CSSValueCover, CSS::PrefixedRadialGradient::Extent { CSS::Keyword::Cover { } } },
        { CSSValueClosestSide, CSS::PrefixedRadialGradient::Extent { CSS::Keyword::ClosestSide { } } },
        { CSSValueClosestCorner, CSS::PrefixedRadialGradient::Extent { CSS::Keyword::ClosestCorner { } } },
        { CSSValueFarthestSide, CSS::PrefixedRadialGradient::Extent { CSS::Keyword::FarthestSide { } } },
        { CSSValueFarthestCorner, CSS::PrefixedRadialGradient::Extent { CSS::Keyword::FarthestCorner { } } },
    };
    static constexpr SortedArrayMap extentMap { extentMappings };

    auto position = consumeOneOrTwoComponentPositionUnresolved(range, context);
    if (position) {
        if (!consumeCommaIncludingWhitespace(range))
            return nullptr;
    }

    std::optional<ShapeKeyword> shapeKeyword;
    std::optional<CSS::PrefixedRadialGradient::Extent> extentKeyword;
    if (range.peek().type() == IdentToken) {
        shapeKeyword = consumeIdentUsingMapping(range, shapeMap);
        extentKeyword = consumeIdentUsingMapping(range, extentMap);
        if (!shapeKeyword)
            shapeKeyword = consumeIdentUsingMapping(range, shapeMap);
        if (shapeKeyword || extentKeyword) {
            if (!consumeCommaIncludingWhitespace(range))
                return nullptr;
        }
    }

    auto consumeGradientBox = [&] -> std::optional<CSS::PrefixedRadialGradient::GradientBox> {
        if (shapeKeyword && extentKeyword) {
            switch (*shapeKeyword) {
            case ShapeKeyword::Ellipse:
                return CSS::PrefixedRadialGradient::Ellipse {
                    .size = *extentKeyword,
                    .position = WTFMove(position),
                };

            case ShapeKeyword::Circle:
                return CSS::PrefixedRadialGradient::Circle {
                    .size = *extentKeyword,
                    .position = WTFMove(position),
                };
            }
        }

        if (shapeKeyword) {
            switch (*shapeKeyword) {
            case ShapeKeyword::Ellipse:
                return CSS::PrefixedRadialGradient::Ellipse {
                    .size = std::nullopt,
                    .position = WTFMove(position),
                };

            case ShapeKeyword::Circle:
                return CSS::PrefixedRadialGradient::Circle {
                    .size = std::nullopt,
                    .position = WTFMove(position),
                };
            }
        }

        if (extentKeyword) {
            return CSS::PrefixedRadialGradient::Ellipse {
                .size = *extentKeyword,
                .position = WTFMove(position),
            };
        }

        const auto options = CSSPropertyParserOptions {
            .parserMode = context.mode,
            .unitlessZero = UnitlessZeroQuirk::Allow
        };

        if (auto length1 = MetaConsumer<CSS::LengthPercentage<CSS::Nonnegative>>::consume(range, context, { }, options)) {
            auto length2 = MetaConsumer<CSS::LengthPercentage<CSS::Nonnegative>>::consume(range, context, { }, options);
            if (!length2)
                return std::nullopt;
            if (!consumeCommaIncludingWhitespace(range))
                return std::nullopt;
            return CSS::PrefixedRadialGradient::Ellipse {
                .size = SpaceSeparatedArray { WTFMove(*length1), WTFMove(*length2) },
                .position = WTFMove(position),
            };
        }

        // If no size is provided, default to an ellipse.
        return CSS::PrefixedRadialGradient::Ellipse {
            .size = std::nullopt,
            .position = WTFMove(position)
        };
    };

    auto gradientBox = consumeGradientBox();
    if (!gradientBox)
        return nullptr;

    auto stops = consumeLinearColorStopList<SupportsColorHints::No>(range, context);
    if (!stops)
        return nullptr;

    return CSSGradientValue::create(
        FunctionNotation<Name, CSS::PrefixedRadialGradient> {
            .parameters = {
                .colorInterpolationMethod = CSS::GradientColorInterpolationMethod::legacyMethod(AlphaPremultiplication::Premultiplied),
                .gradientBox = WTFMove(*gradientBox),
                .stops = WTFMove(*stops)
            }
        }
    );
}

// MARK: Standard <gradient> values

// MARK: <linear-gradient()> | <repeating-linear-gradient()>
// https://drafts.csswg.org/css-images-4/#linear-gradients

template<CSSValueID Name> static RefPtr<CSSValue> consumeLinearGradient(CSSParserTokenRange& range, const CSSParserContext& context)
{
    // <side-or-corner> = [left | right] || [top | bottom]
    // linear-gradient() = linear-gradient(
    //   [ <angle> | to <side-or-corner> ]? || <color-interpolation-method>,
    //   <color-stop-list>
    // )

    static constexpr std::pair<CSSValueID, CSS::Vertical> verticalMappings[] {
        { CSSValueTop, CSS::Vertical { CSS::Keyword::Top { } } },
        { CSSValueBottom, CSS::Vertical { CSS::Keyword::Bottom { } } },
    };
    static constexpr SortedArrayMap verticalMap { verticalMappings };

    static constexpr std::pair<CSSValueID, CSS::Horizontal> horizontalMappings[] {
        { CSSValueLeft, CSS::Horizontal { CSS::Keyword::Left { } } },
        { CSSValueRight, CSS::Horizontal { CSS::Keyword::Right { } } },
    };
    static constexpr SortedArrayMap horizontalMap { horizontalMappings };

    auto consumeKeywordGradientLineKnownHorizontal = [&](CSSParserTokenRange& range, CSS::Horizontal knownHorizontal) -> CSS::LinearGradient::GradientLine {
        if (auto vertical = consumeIdentUsingMapping(range, verticalMap))
            return SpaceSeparatedTuple { knownHorizontal, *vertical };
        return knownHorizontal;
    };

    auto consumeKeywordGradientLineKnownVertical = [&](CSSParserTokenRange& range, CSS::Vertical knownVertical) -> CSS::LinearGradient::GradientLine {
        if (auto horizontal = consumeIdentUsingMapping(range, horizontalMap))
            return SpaceSeparatedTuple { *horizontal, knownVertical };
        return knownVertical;
    };

    auto consumeKeywordGradientLine = [&](CSSParserTokenRange& range) -> std::optional<CSS::LinearGradient::GradientLine> {
        ASSERT(range.peek().id() == CSSValueTo);
        range.consumeIncludingWhitespace();

        switch (range.peek().id()) {
        case CSSValueLeft:
            range.consumeIncludingWhitespace();
            return consumeKeywordGradientLineKnownHorizontal(range, CSS::Horizontal { CSS::Keyword::Left { } });
        case CSSValueRight:
            range.consumeIncludingWhitespace();
            return consumeKeywordGradientLineKnownHorizontal(range, CSS::Horizontal { CSS::Keyword::Right { } });
        case CSSValueTop:
            range.consumeIncludingWhitespace();
            return consumeKeywordGradientLineKnownVertical(range, CSS::Vertical { CSS::Keyword::Top { } });
        case CSSValueBottom:
            range.consumeIncludingWhitespace();
            return consumeKeywordGradientLineKnownVertical(range, CSS::Vertical { CSS::Keyword::Bottom { } });
        default:
            return { };
        }
    };

    std::optional<ColorInterpolationMethod> colorInterpolationMethod;

    if (range.peek().id() == CSSValueIn) {
        colorInterpolationMethod = consumeColorInterpolationMethod(range, context);
        if (!colorInterpolationMethod)
            return nullptr;
    }

    std::optional<CSS::LinearGradient::GradientLine> gradientLine;

    const auto angleConsumeOptions = CSSPropertyParserOptions {
        .parserMode = context.mode,
        .unitless = UnitlessQuirk::Forbid,
        .unitlessZero = UnitlessZeroQuirk::Allow
    };

    if (auto angle = MetaConsumer<CSS::Angle<>>::consume(range, context, { }, angleConsumeOptions))
        gradientLine = WTFMove(angle);
    else if (range.peek().id() == CSSValueTo) {
        auto keywordGradientLine = consumeKeywordGradientLine(range);
        if (!keywordGradientLine)
            return nullptr;
        gradientLine = WTFMove(*keywordGradientLine);
    }

    if (gradientLine && !colorInterpolationMethod && range.peek().id() == CSSValueIn) {
        colorInterpolationMethod = consumeColorInterpolationMethod(range, context);
        if (!colorInterpolationMethod)
            return nullptr;
    }

    if (gradientLine || colorInterpolationMethod) {
        if (!consumeCommaIncludingWhitespace(range))
            return nullptr;
    }

    auto stops = consumeLinearColorStopList<SupportsColorHints::Yes>(range, context);
    if (!stops)
        return nullptr;

    auto computedColorInterpolationMethod = computeGradientColorInterpolationMethod(colorInterpolationMethod, *stops);

    return CSSGradientValue::create(
        FunctionNotation<Name, CSS::LinearGradient> {
            .parameters = {
                .colorInterpolationMethod = computedColorInterpolationMethod,
                .gradientLine = gradientLine.value_or(CSS::Vertical { CSS::Keyword::Bottom { } }),
                .stops = WTFMove(*stops)
            }
        }
    );
}

// MARK: <radial-gradient()> | <repeating-radial-gradient()>
// https://drafts.csswg.org/css-images-4/#radial-gradients

template<CSSValueID Name> static RefPtr<CSSValue> consumeRadialGradient(CSSParserTokenRange& range, const CSSParserContext& context)
{
    // radial-gradient() = radial-gradient(
    //   [[ <ending-shape> || <size> ]? [ at <position> ]? ] || <color-interpolation-method>,
    //   <color-stop-list>
    // )

    static constexpr std::pair<CSSValueID, ShapeKeyword> shapeMappings[] {
        { CSSValueCircle, ShapeKeyword::Circle },
        { CSSValueEllipse, ShapeKeyword::Ellipse },
    };
    static constexpr SortedArrayMap shapeMap { shapeMappings };

    static constexpr std::pair<CSSValueID, CSS::RadialGradient::Extent> extentMappings[] {
        { CSSValueClosestSide, CSS::RadialGradient::Extent { CSS::Keyword::ClosestSide { } } },
        { CSSValueClosestCorner, CSS::RadialGradient::Extent { CSS::Keyword::ClosestCorner { } } },
        { CSSValueFarthestSide, CSS::RadialGradient::Extent { CSS::Keyword::FarthestSide { } } },
        { CSSValueFarthestCorner, CSS::RadialGradient::Extent { CSS::Keyword::FarthestCorner { } } },
    };
    static constexpr SortedArrayMap extentMap { extentMappings };

    static constexpr auto defaultExtent = CSS::RadialGradient::Extent { CSS::Keyword::FarthestCorner { } };

    std::optional<ColorInterpolationMethod> colorInterpolationMethod;

    if (range.peek().id() == CSSValueIn) {
        colorInterpolationMethod = consumeColorInterpolationMethod(range, context);
        if (!colorInterpolationMethod)
            return nullptr;
    }

    std::optional<ShapeKeyword> shape;

    using Size = std::variant<CSS::RadialGradient::Extent, CSS::Length<CSS::Nonnegative>, SpaceSeparatedArray<CSS::LengthPercentage<CSS::Nonnegative>, 2>>;
    std::optional<Size> size;

    // First part of grammar, the size/shape clause:
    //
    //   [ [ circle               || <length [0,∞]> ]                          [ at <position> ]? , |
    //     [ ellipse              || <length-percentage [0,∞]>{2} ]            [ at <position> ]? , |
    //     [ [ circle | ellipse ] || <extent-keyword> ]                        [ at <position> ]? , |
    //     at <position> ,
    //   ]?
    for (int i = 0; i < 3; ++i) {
        if (range.peek().type() == IdentToken) {
            if (auto peekedShape = peekIdentUsingMapping(range, shapeMap)) {
                if (shape)
                    return nullptr;
                shape = *peekedShape;
                range.consumeIncludingWhitespace();
            } else if (auto peekedExtent = peekIdentUsingMapping(range, extentMap)) {
                if (size)
                    return nullptr;
                size = *peekedExtent;
                range.consumeIncludingWhitespace();
            }

            if (!shape && !size)
                break;
        } else {
            const auto options = CSSPropertyParserOptions {
                .parserMode = context.mode,
                .unitlessZero = UnitlessZeroQuirk::Allow
            };
            auto rangeCopy = range;
            auto length1 = MetaConsumer<CSS::LengthPercentage<CSS::Nonnegative>>::consume(rangeCopy, context, { }, options);
            if (!length1)
                break;
            if (size)
                return nullptr;
            if (auto length2 = MetaConsumer<CSS::LengthPercentage<CSS::Nonnegative>>::consume(rangeCopy, context, { }, options)) {
                size = SpaceSeparatedArray { WTFMove(*length1), WTFMove(*length2) };
                range = rangeCopy;

                // Additional increment is necessary since we consumed a second token.
                ++i;
            } else {
                // Reset to before the first length-percentage, and re-parse to make sure it is a valid <length [0,∞]> production.
                rangeCopy = range;
                auto length = MetaConsumer<CSS::Length<CSS::Nonnegative>>::consume(rangeCopy, context, { }, options);
                if (!length)
                    return nullptr;
                size = WTFMove(*length);
                range = rangeCopy;
            }
        }
    }

    std::optional<CSS::Position> position;
    if (consumeIdent<CSSValueAt>(range)) {
        position = consumePositionUnresolved(range, context);
        if (!position)
            return nullptr;
    }

    if ((shape || size || position) && !colorInterpolationMethod && range.peek().id() == CSSValueIn) {
        colorInterpolationMethod = consumeColorInterpolationMethod(range, context);
        if (!colorInterpolationMethod)
            return nullptr;
    }

    if ((shape || size || position || colorInterpolationMethod) && !consumeCommaIncludingWhitespace(range))
        return nullptr;

    auto stops = consumeLinearColorStopList<SupportsColorHints::Yes>(range, context);
    if (!stops)
        return nullptr;

    auto consumeGradientBox = [&] -> std::optional<CSS::RadialGradient::GradientBox> {
        if (shape && size) {
            switch (*shape) {
            case ShapeKeyword::Ellipse:
                return WTF::switchOn(WTFMove(*size),
                    [&](CSS::RadialGradient::Extent&& extent) -> std::optional<CSS::RadialGradient::GradientBox> {
                        return CSS::RadialGradient::Ellipse {
                            .size = WTFMove(extent),
                            .position = WTFMove(position),
                        };
                    },
                    [&](CSS::Length<CSS::Nonnegative>&&) -> std::optional<CSS::RadialGradient::GradientBox> {
                        // Ellipses must have two length-percentages specified.
                        return std::nullopt;
                    },
                    [&](SpaceSeparatedArray<CSS::LengthPercentage<CSS::Nonnegative>, 2>&& size) -> std::optional<CSS::RadialGradient::GradientBox> {
                        return CSS::RadialGradient::Ellipse {
                            .size = WTFMove(size),
                            .position = WTFMove(position),
                        };
                    }
                );

            case ShapeKeyword::Circle:
                return WTF::switchOn(WTFMove(*size),
                    [&](CSS::RadialGradient::Extent&& extent) -> std::optional<CSS::RadialGradient::GradientBox> {
                        return CSS::RadialGradient::Circle {
                            .size = WTFMove(extent),
                            .position = WTFMove(position),
                        };
                    },
                    [&](CSS::Length<CSS::Nonnegative>&& length) -> std::optional<CSS::RadialGradient::GradientBox> {
                        return CSS::RadialGradient::Circle {
                            .size = WTFMove(length),
                            .position = WTFMove(position),
                        };
                    },
                    [&](SpaceSeparatedArray<CSS::LengthPercentage<CSS::Nonnegative>, 2>&&) -> std::optional<CSS::RadialGradient::GradientBox> {
                        // Circles must have a maximum of only one length specified.
                        return std::nullopt;
                    }
                );
            }
        }

        if (shape) {
            switch (*shape) {
            case ShapeKeyword::Ellipse:
                return CSS::RadialGradient::Ellipse {
                    .size = defaultExtent,
                    .position = WTFMove(position),
                };

            case ShapeKeyword::Circle:
                return CSS::RadialGradient::Circle {
                    .size = defaultExtent,
                    .position = WTFMove(position),
                };
            }
        }

        if (size) {
            return WTF::switchOn(WTFMove(*size),
                [&](CSS::RadialGradient::Extent&& extent) -> std::optional<CSS::RadialGradient::GradientBox> {
                    return CSS::RadialGradient::Ellipse {
                        .size = WTFMove(extent),
                        .position = WTFMove(position),
                    };
                },
                [&](CSS::Length<CSS::Nonnegative>&& length) -> std::optional<CSS::RadialGradient::GradientBox> {
                    return CSS::RadialGradient::Circle {
                        .size = WTFMove(length),
                        .position = WTFMove(position),
                    };
                },
                [&](SpaceSeparatedArray<CSS::LengthPercentage<CSS::Nonnegative>, 2>&& size) -> std::optional<CSS::RadialGradient::GradientBox> {
                    return CSS::RadialGradient::Ellipse {
                        .size = WTFMove(size),
                        .position = WTFMove(position),
                    };
                }
            );
        }

        // If no size is provided, default to an ellipse.
        return CSS::RadialGradient::Ellipse {
            .size = defaultExtent,
            .position = WTFMove(position),
        };
    };

    auto gradientBox = consumeGradientBox();
    if (!gradientBox)
        return nullptr;

    auto computedColorInterpolationMethod = computeGradientColorInterpolationMethod(colorInterpolationMethod, *stops);

    return CSSGradientValue::create(
        FunctionNotation<Name, CSS::RadialGradient> {
            .parameters = {
                .colorInterpolationMethod = computedColorInterpolationMethod,
                .gradientBox = WTFMove(*gradientBox),
                .stops = WTFMove(*stops)
            }
        }
    );
}

// MARK: <conic-gradient()> | <repeating-conic-gradient()>
// https://drafts.csswg.org/css-images-4/#conic-gradient-syntax

template<CSSValueID Name> static RefPtr<CSSValue> consumeConicGradient(CSSParserTokenRange& range, const CSSParserContext& context)
{
    // conic-gradient() = conic-gradient(
    //   [ [ from <angle> ]? [ at <position> ]? ] || <color-interpolation-method>,
    //   <angular-color-stop-list>
    // )

    std::optional<ColorInterpolationMethod> colorInterpolationMethod;

    if (range.peek().id() == CSSValueIn) {
        colorInterpolationMethod = consumeColorInterpolationMethod(range, context);
        if (!colorInterpolationMethod)
            return nullptr;
    }

    std::optional<CSS::Angle<>> angle;
    if (consumeIdent<CSSValueFrom>(range)) {
        const auto angleConsumeOptions = CSSPropertyParserOptions {
            .parserMode = context.mode,
            .unitless = UnitlessQuirk::Forbid,
            .unitlessZero = UnitlessZeroQuirk::Allow
        };
        angle = MetaConsumer<CSS::Angle<>>::consume(range, context, { }, angleConsumeOptions);
        if (!angle)
            return nullptr;
    }

    std::optional<CSS::Position> position;
    if (consumeIdent<CSSValueAt>(range)) {
        position = consumePositionUnresolved(range, context);
        if (!position)
            return nullptr;
    }

    if ((angle || position) && !colorInterpolationMethod && range.peek().id() == CSSValueIn) {
        colorInterpolationMethod = consumeColorInterpolationMethod(range, context);
        if (!colorInterpolationMethod)
            return nullptr;
    }

    if (angle || position || colorInterpolationMethod) {
        if (!consumeCommaIncludingWhitespace(range))
            return nullptr;
    }

    auto stops = consumeAngularColorStopList<SupportsColorHints::Yes>(range, context);
    if (!stops)
        return nullptr;

    auto computedColorInterpolationMethod = computeGradientColorInterpolationMethod(colorInterpolationMethod, *stops);

    return CSSGradientValue::create(
        FunctionNotation<Name, CSS::ConicGradient> {
            .parameters = {
                .colorInterpolationMethod = computedColorInterpolationMethod,
                .gradientBox = {
                    .angle = WTFMove(angle),
                    .position = WTFMove(position),
                },
                .stops = WTFMove(*stops),
            }
        }
    );
}

// MARK: <cross-fade()>

static RefPtr<CSSValue> consumeCrossFade(CSSParserTokenRange& args, const CSSParserContext& context, CSSValueID functionId)
{
    // FIXME: The current CSS Images spec has a pretty different construction than is being parsed here:
    //
    //    cross-fade() = cross-fade( <cf-image># )
    //    <cf-image> = <percentage [0,100]>? && [ <image> | <color> ]
    //
    //  https://drafts.csswg.org/css-images-4/#funcdef-cross-fade

    auto fromImageValueOrNone = consumeImageOrNone(args, context);
    if (!fromImageValueOrNone || !consumeCommaIncludingWhitespace(args))
        return nullptr;
    auto toImageValueOrNone = consumeImageOrNone(args, context);
    if (!toImageValueOrNone || !consumeCommaIncludingWhitespace(args))
        return nullptr;

    auto value = consumePercentageDividedBy100OrNumber(args, context);
    if (!value)
        return nullptr;

    if (value->isNumber()) {
        if (auto numberValue = value->resolveAsNumberIfNotCalculated(); numberValue && (*numberValue < 0 || *numberValue > 1))
            value = CSSPrimitiveValue::create(clampTo<double>(*numberValue, 0, 1));
    }
    return CSSCrossfadeValue::create(fromImageValueOrNone.releaseNonNull(), toImageValueOrNone.releaseNonNull(), value.releaseNonNull(), functionId == CSSValueWebkitCrossFade);
}

// MARK: <-webkit-canvas()>

static RefPtr<CSSValue> consumeWebkitCanvas(CSSParserTokenRange& args)
{
    if (args.peek().type() != IdentToken)
        return nullptr;
    return CSSCanvasValue::create(args.consumeIncludingWhitespace().value().toString());
}

// MARK: <-webkit-named-image()>

static RefPtr<CSSValue> consumeWebkitNamedImage(CSSParserTokenRange& args)
{
    if (args.peek().type() != IdentToken)
        return nullptr;
    return CSSNamedImageValue::create(args.consumeIncludingWhitespace().value().toString());
}

// MARK: <filter()>

static RefPtr<CSSValue> consumeFilterImage(CSSParserTokenRange& args, const CSSParserContext& context)
{
    // FIXME: The current Filter Effects spec has a different construction than is being parsed here:
    //
    //    filter() = filter( [ <image> | <string> ], <filter-value-list> )
    //
    //  https://drafts.fxtf.org/filter-effects/#funcdef-filter
    //
    // Importantly, `none` is not a valid value for either parameter.

    auto imageValueOrNone = consumeImageOrNone(args, context);
    if (!imageValueOrNone || !consumeCommaIncludingWhitespace(args))
        return nullptr;
    auto filter = consumeUnresolvedFilter(args, context);
    if (!filter)
        return nullptr;
    return CSSFilterImageValue::create(imageValueOrNone.releaseNonNull(), WTFMove(*filter));
}

// MARK: <paint()>
// https://drafts.css-houdini.org/css-paint-api/#funcdef-paint

static RefPtr<CSSValue> consumeCustomPaint(CSSParserTokenRange& args, const CSSParserContext& context)
{
    if (!context.cssPaintingAPIEnabled)
        return nullptr;
    if (args.peek().type() != IdentToken)
        return nullptr;
    auto name = args.consumeIncludingWhitespace().value().toString();

    if (!args.atEnd() && args.peek() != CommaToken)
        return nullptr;
    if (!args.atEnd())
        args.consume();

    auto argumentList = CSSVariableData::create(args.consumeAll());
    return CSSPaintImageValue::create(name, WTFMove(argumentList));
}

// MARK: <image-set()>

struct ImageSetTypeFunctionRaw {
    String value;

    bool operator==(const ImageSetTypeFunctionRaw&) const = default;
};
using ImageSetTypeFunction = ImageSetTypeFunctionRaw;

struct ImageSetTypeFunctionRawKnownTokenTypeFunctionConsumer {
    static constexpr CSSParserTokenType tokenType = FunctionToken;

    static std::optional<ImageSetTypeFunctionRaw> consume(CSSParserTokenRange& range, const CSSParserContext&, CSSCalcSymbolsAllowed, CSSPropertyParserOptions)
    {
        ASSERT(range.peek().type() == FunctionToken);
        if (range.peek().functionId() != CSSValueType)
            return { };

        auto rangeCopy = range;
        auto typeArg = consumeFunction(rangeCopy);
        auto result = consumeStringRaw(typeArg);

        if (result.isNull() || !typeArg.atEnd())
            return { };

        range = rangeCopy;
        return { { result.toString() } };
    }
};

template<> struct ConsumerDefinition<ImageSetTypeFunction> {
    using FunctionToken = ImageSetTypeFunctionRawKnownTokenTypeFunctionConsumer;
};

// MARK: Image Set Resolution + Type Function

static RefPtr<CSSPrimitiveValue> consumeImageSetResolutionOrTypeFunction(CSSParserTokenRange& range, const CSSParserContext& context)
{
    // [ <resolution> || type(<string>) ]
    //
    //   as part of
    //
    // <image-set()> = image-set( <image-set-option># )
    // <image-set-option> = [ <image> | <string> ] [ <resolution> || type(<string>) ]?

    const auto options = CSSPropertyParserOptions {
        .unitless = UnitlessQuirk::Allow,
        .unitlessZero = UnitlessZeroQuirk::Allow
    };

    return MetaConsumer<CSS::Resolution<>, ImageSetTypeFunction>::consume(range, context, { }, options,
        [&](const ImageSetTypeFunction& typeFunction) -> RefPtr<CSSPrimitiveValue> {
            return CSSPrimitiveValue::create(typeFunction.value);
        },
        [&](const CSS::Resolution<>& resolution) -> RefPtr<CSSPrimitiveValue> {
            return CSSPrimitiveValueResolverBase::resolve(resolution, options);
        }
    ).value_or(nullptr);
}

// https://w3c.github.io/csswg-drafts/css-images-4/#image-set-notation
static RefPtr<CSSImageSetOptionValue> consumeImageSetOption(CSSParserTokenRange& range, const CSSParserContext& context, OptionSet<AllowedImageType> allowedImageTypes)
{
    auto image = consumeImage(range, context, allowedImageTypes);
    if (!image)
        return nullptr;

    auto result = CSSImageSetOptionValue::create(image.releaseNonNull());

    RefPtr<CSSPrimitiveValue> resolution;
    RefPtr<CSSPrimitiveValue> type;

    // Optional resolution and type in any order.
    for (size_t i = 0; i < 2 && !range.atEnd(); ++i) {
        if (auto optionalArgument = consumeImageSetResolutionOrTypeFunction(range, context)) {
            if ((resolution && optionalArgument->isResolution()) || (type && optionalArgument->isString()))
                return nullptr;

            if (optionalArgument->isResolution()) {
                resolution = optionalArgument;
                result->setResolution(optionalArgument.releaseNonNull());
                continue;
            }

            if (optionalArgument->isString()) {
                type = optionalArgument;
                result->setType(type->stringValue());
                continue;
            }
        }
        break;
    }

    if (!range.atEnd() && range.peek().type() != CommaToken)
        return nullptr;
    return result;
}


static RefPtr<CSSValue> consumeImageSet(CSSParserTokenRange& args, const CSSParserContext& context, OptionSet<AllowedImageType> allowedImageTypes)
{
    CSSValueListBuilder imageSet;
    do {
        if (auto option = consumeImageSetOption(args, context, allowedImageTypes))
            imageSet.append(option.releaseNonNull());
        else
            return nullptr;
    } while (consumeCommaIncludingWhitespace(args));

    return CSSImageSetValue::create(WTFMove(imageSet));
}

// MARK: <image>
// https://drafts.csswg.org/css-images-4/#image-values

RefPtr<CSSValue> consumeImage(CSSParserTokenRange& range, const CSSParserContext& context, OptionSet<AllowedImageType> allowedImageTypes)
{
    if (range.peek().type() == StringToken && allowedImageTypes.contains(AllowedImageType::RawStringAsURL)) {
        return CSSImageValue::create(context.completeURL(range.consumeIncludingWhitespace().value().toAtomString().string()),
            context.isContentOpaque ? LoadedFromOpaqueSource::Yes : LoadedFromOpaqueSource::No);
    }

    if (range.peek().type() == FunctionToken) {
        auto consumeGeneratedImage = [&](auto consumer) -> RefPtr<CSSValue> {
            if (!allowedImageTypes.contains(AllowedImageType::GeneratedImage))
                return nullptr;
            CSSParserTokenRange rangeCopy = range;
            CSSParserTokenRange args = consumeFunction(rangeCopy);
            RefPtr result = consumer(args);
            if (!result || !args.atEnd())
                return nullptr;
            range = rangeCopy;
            return result;
        };

        auto consumeImageSetImage = [&](auto consumer) -> RefPtr<CSSValue> {
            if (!allowedImageTypes.contains(AllowedImageType::ImageSet))
                return nullptr;
            CSSParserTokenRange rangeCopy = range;
            CSSParserTokenRange args = consumeFunction(rangeCopy);
            RefPtr result = consumer(args);
            if (!result || !args.atEnd())
                return nullptr;
            range = rangeCopy;
            return result;
        };

        auto functionId = range.peek().functionId();
        switch (functionId) {
        case CSSValueRadialGradient:
            return consumeGeneratedImage([&](auto& args) { return consumeRadialGradient<CSSValueRadialGradient>(args, context); });
        case CSSValueRepeatingRadialGradient:
            return consumeGeneratedImage([&](auto& args) { return consumeRadialGradient<CSSValueRepeatingRadialGradient>(args, context); });
        case CSSValueWebkitLinearGradient:
            return consumeGeneratedImage([&](auto& args) { return consumePrefixedLinearGradient<CSSValueWebkitLinearGradient>(args, context); });
        case CSSValueWebkitRepeatingLinearGradient:
            return consumeGeneratedImage([&](auto& args) { return consumePrefixedLinearGradient<CSSValueWebkitRepeatingLinearGradient>(args, context); });
        case CSSValueRepeatingLinearGradient:
            return consumeGeneratedImage([&](auto& args) { return consumeLinearGradient<CSSValueRepeatingLinearGradient>(args, context); });
        case CSSValueLinearGradient:
            return consumeGeneratedImage([&](auto& args) { return consumeLinearGradient<CSSValueLinearGradient>(args, context); });
        case CSSValueWebkitGradient:
            return consumeGeneratedImage([&](auto& args) { return consumeDeprecatedGradient(args, context); });
        case CSSValueWebkitRadialGradient:
            return consumeGeneratedImage([&](auto& args) { return consumePrefixedRadialGradient<CSSValueWebkitRadialGradient>(args, context); });
        case CSSValueWebkitRepeatingRadialGradient:
            return consumeGeneratedImage([&](auto& args) { return consumePrefixedRadialGradient<CSSValueWebkitRepeatingRadialGradient>(args, context); });
        case CSSValueConicGradient:
            return consumeGeneratedImage([&](auto& args) { return consumeConicGradient<CSSValueConicGradient>(args, context); });
        case CSSValueRepeatingConicGradient:
            return consumeGeneratedImage([&](auto& args) { return consumeConicGradient<CSSValueRepeatingConicGradient>(args, context); });
        case CSSValueWebkitCrossFade:
            return consumeGeneratedImage([&](auto& args) { return consumeCrossFade(args, context, functionId); });
        case CSSValueCrossFade:
            return consumeGeneratedImage([&](auto& args) { return consumeCrossFade(args, context, functionId); });
        case CSSValueWebkitCanvas:
            return consumeGeneratedImage([&](auto& args) { return consumeWebkitCanvas(args); });
        case CSSValueWebkitNamedImage:
            return consumeGeneratedImage([&](auto& args) { return consumeWebkitNamedImage(args); });
        case CSSValueWebkitFilter:
        case CSSValueFilter:
            return consumeGeneratedImage([&](auto& args) { return consumeFilterImage(args, context); });
        case CSSValuePaint:
            return consumeGeneratedImage([&](auto& args) { return consumeCustomPaint(args, context); });
        case CSSValueImageSet:
        case CSSValueWebkitImageSet:
            return consumeImageSetImage([&](auto& args) { return consumeImageSet(args, context, (allowedImageTypes | AllowedImageType::RawStringAsURL) - AllowedImageType::ImageSet); });
        default:
            break;
        }
    }

    if (allowedImageTypes.contains(AllowedImageType::URLFunction)) {
        if (auto string = consumeURLRaw(range); !string.isNull()) {
            return CSSImageValue::create(context.completeURL(string.toAtomString().string()),
                context.isContentOpaque ? LoadedFromOpaqueSource::Yes : LoadedFromOpaqueSource::No);
        }
    }

    return nullptr;
}

// MARK: <image> | none

RefPtr<CSSValue> consumeImageOrNone(CSSParserTokenRange& range, const CSSParserContext& context, OptionSet<AllowedImageType> allowedImageTypes)
{
    if (range.peek().id() == CSSValueNone)
        return consumeIdent(range);
    return consumeImage(range, context, allowedImageTypes);
}

} // namespace CSSPropertyParserHelpers
} // namespace WebCore