File: CSSPropertyParser.cpp

package info (click to toggle)
webkit2gtk 2.50.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 445,780 kB
  • sloc: cpp: 3,798,013; javascript: 197,914; ansic: 161,337; python: 49,141; asm: 21,990; ruby: 18,540; perl: 16,723; xml: 4,623; yacc: 2,360; sh: 2,246; java: 2,019; lex: 1,327; pascal: 366; makefile: 298
file content (820 lines) | stat: -rw-r--r-- 33,192 bytes parent folder | download | duplicates (4)
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
// Copyright 2015 The Chromium Authors. All rights reserved.
// Copyright (C) 2016-2022 Apple Inc. All rights reserved.
// Copyright (C) 2024-2025 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:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * 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.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "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 THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR 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 "CSSPropertyParser.h"

#include "CSSCustomPropertySyntax.h"
#include "CSSCustomPropertyValue.h"
#include "CSSMarkup.h"
#include "CSSParserContext.h"
#include "CSSParserFastPaths.h"
#include "CSSParserIdioms.h"
#include "CSSParserTokenRange.h"
#include "CSSPendingSubstitutionValue.h"
#include "CSSPrimitiveValue.h"
#include "CSSPropertyParserConsumer+AngleDefinitions.h"
#include "CSSPropertyParserConsumer+CSSPrimitiveValueResolver.h"
#include "CSSPropertyParserConsumer+Ident.h"
#include "CSSPropertyParserConsumer+Image.h"
#include "CSSPropertyParserConsumer+IntegerDefinitions.h"
#include "CSSPropertyParserConsumer+LengthDefinitions.h"
#include "CSSPropertyParserConsumer+LengthPercentageDefinitions.h"
#include "CSSPropertyParserConsumer+List.h"
#include "CSSPropertyParserConsumer+NumberDefinitions.h"
#include "CSSPropertyParserConsumer+PercentageDefinitions.h"
#include "CSSPropertyParserConsumer+ResolutionDefinitions.h"
#include "CSSPropertyParserConsumer+String.h"
#include "CSSPropertyParserConsumer+TimeDefinitions.h"
#include "CSSPropertyParserConsumer+URL.h"
#include "CSSPropertyParserResult.h"
#include "CSSPropertyParserState.h"
#include "CSSPropertyParsing.h"
#include "CSSTokenizer.h"
#include "CSSTransformListValue.h"
#include "CSSVariableParser.h"
#include "CSSVariableReferenceValue.h"
#include "CSSWideKeyword.h"
#include "ComputedStyleDependencies.h"
#include "StyleBuilder.h"
#include "StyleBuilderConverter.h"
#include "StyleCustomProperty.h"
#include "StylePropertyShorthand.h"
#include "StylePropertyShorthandFunctions.h"
#include "StyleRuleType.h"
#include "TransformOperationsBuilder.h"
#include <memory>
#include <wtf/StdLibExtras.h>
#include <wtf/text/ParsingUtilities.h>
#include <wtf/text/StringView.h>

namespace WebCore {

// MARK: - Custom properties

static std::pair<RefPtr<CSSValue>, CSSCustomPropertySyntax::Type> consumeCustomPropertyValueWithSyntax(CSSParserTokenRange&, CSS::PropertyParserState&, const CSSCustomPropertySyntax&);
static std::optional<Variant<Ref<const Style::CustomProperty>, CSSWideKeyword>> consumeTypedCustomPropertyValue(CSSParserTokenRange&, CSS::PropertyParserState&, const AtomString& name, const CSSCustomPropertySyntax&, Style::BuilderState&);

// MARK: - Root consumers

// Style properties.
static bool consumeStyleProperty(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, IsImportant, StyleRuleType, CSS::PropertyParserResult&);

// @font-face descriptors.
static bool consumeFontFaceDescriptor(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, CSS::PropertyParserResult&);

// @font-palette-values descriptors.
static bool consumeFontPaletteValuesDescriptor(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, CSS::PropertyParserResult&);

// @counter-style descriptors.
static bool consumeCounterStyleDescriptor(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, CSS::PropertyParserResult&);

// @keyframe descriptors.
static bool consumeKeyframeDescriptor(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, IsImportant, CSS::PropertyParserResult&);

// @page descriptors.
static bool consumePageDescriptor(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, IsImportant, CSS::PropertyParserResult&);

// @property descriptors.
static bool consumePropertyDescriptor(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, CSS::PropertyParserResult&);

// @view-transition descriptors.
static bool consumeViewTransitionDescriptor(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, CSS::PropertyParserResult&);

// @position-try descriptors.
static bool consumePositionTryDescriptor(CSSParserTokenRange&, const CSSParserContext&, CSSPropertyID, IsImportant, CSS::PropertyParserResult&);

// MARK: - CSSPropertyID parsing

template<typename CharacterType> static CSSPropertyID cssPropertyID(std::span<const CharacterType> characters)
{
    std::array<char, maxCSSPropertyNameLength> buffer;
    for (size_t i = 0; i != characters.size(); ++i) {
        auto character = characters[i];
        if (!character || !isASCII(character))
            return CSSPropertyInvalid;
        buffer[i] = toASCIILower(character);
    }
    return findCSSProperty(buffer.data(), characters.size());
}

CSSPropertyID cssPropertyID(StringView string)
{
    auto length = string.length();
    if (!length)
        return CSSPropertyInvalid;
    if (length > maxCSSPropertyNameLength)
        return CSSPropertyInvalid;
    return string.is8Bit() ? cssPropertyID(string.span8()) : cssPropertyID(string.span16());
}

// MARK: - CSSValueID parsing

// FIXME: Remove this mechanism entirely once we can do it without breaking the web.
static bool isAppleLegacyCSSValueKeyword(std::span<const char> characters)
{
    return spanHasPrefix(characters.subspan(1), "apple-"_span)
        && !spanHasPrefix(characters.subspan(7), "system"_span)
        && !spanHasPrefix(characters.subspan(7), "pay"_span)
        && !spanHasPrefix(characters.subspan(7), "wireless"_span);
}

template<typename CharacterType> static CSSValueID cssValueKeywordID(std::span<const CharacterType> characters)
{
    ASSERT(!characters.empty()); // Otherwise buffer[0] would access uninitialized memory below.

    std::array<char, maxCSSValueKeywordLength + 1> buffer; // 1 to turn "apple" into "webkit"
    
    for (unsigned i = 0; i != characters.size(); ++i) {
        auto character = characters[i];
        if (!character || !isASCII(character))
            return CSSValueInvalid;
        buffer[i] = toASCIILower(character);
    }

    // In most cases, if the prefix is -apple-, change it to -webkit-. This makes the string one character longer.
    auto length = characters.size();
    std::span bufferSpan { buffer };
    if (buffer[0] == '-' && isAppleLegacyCSSValueKeyword(bufferSpan.first(length))) {
        memmoveSpan(bufferSpan.subspan(7), bufferSpan.subspan(6, length - 6));
        memcpySpan(bufferSpan.subspan(1), "webkit"_span);
        ++length;
    }

    return findCSSValueKeyword(bufferSpan.first(length));
}

CSSValueID cssValueKeywordID(StringView string)
{
    unsigned length = string.length();
    if (!length)
        return CSSValueInvalid;
    if (length > maxCSSValueKeywordLength)
        return CSSValueInvalid;
    
    return string.is8Bit() ? cssValueKeywordID(string.span8()) : cssValueKeywordID(string.span16());
}

// MARK: - Custom property name validation

bool isCustomPropertyName(StringView propertyName)
{
    return propertyName.length() > 2 && propertyName.characterAt(0) == '-' && propertyName.characterAt(1) == '-';
}

// MARK: - CSS-wide keyword value consumer

static RefPtr<CSSPrimitiveValue> consumeCSSWideKeywordValue(CSSParserTokenRange& range)
{
    auto rangeCopy = range;
    auto valueID = rangeCopy.consumeIncludingWhitespace().id();
    if (!rangeCopy.atEnd())
        return nullptr;

    if (!isCSSWideKeyword(valueID))
        return nullptr;

    range = rangeCopy;
    return CSSPrimitiveValue::create(valueID);
}

static std::optional<CSSWideKeyword> consumeCSSWideKeyword(CSSParserTokenRange& range)
{
    auto rangeCopy = range;
    auto valueID = rangeCopy.consumeIncludingWhitespace().id();
    if (!rangeCopy.atEnd())
        return { };

    auto keyword = parseCSSWideKeyword(valueID);
    if (!keyword)
        return { };

    range = rangeCopy;
    return keyword;
}

// MARK: - Parser entry points

using namespace CSSPropertyParserHelpers;

bool CSSPropertyParser::parseValue(CSSPropertyID property, IsImportant important, CSSParserTokenRange range, const CSSParserContext& context, ParsedPropertyVector& parsedProperties, StyleRuleType ruleType)
{
    int initialParsedPropertiesSize = parsedProperties.size();

    range.consumeWhitespace();

    CSS::PropertyParserResult result { parsedProperties };

    bool parseSuccess;
    switch (ruleType) {
    case StyleRuleType::CounterStyle:
        parseSuccess = consumeCounterStyleDescriptor(range, context, property, result);
        break;
    case StyleRuleType::FontFace:
        parseSuccess = consumeFontFaceDescriptor(range, context, property, result);
        break;
    case StyleRuleType::FontPaletteValues:
        parseSuccess = consumeFontPaletteValuesDescriptor(range, context, property, result);
        break;
    case StyleRuleType::Keyframe:
        parseSuccess = consumeKeyframeDescriptor(range, context, property, important, result);
        break;
    case StyleRuleType::Page:
        parseSuccess = consumePageDescriptor(range, context, property, important, result);
        break;
    case StyleRuleType::Property:
        parseSuccess = consumePropertyDescriptor(range, context, property, result);
        break;
    case StyleRuleType::ViewTransition:
        parseSuccess = consumeViewTransitionDescriptor(range, context, property, result);
        break;
    case StyleRuleType::PositionTry:
        parseSuccess = consumePositionTryDescriptor(range, context, property, important, result);
        break;
    default:
        parseSuccess = consumeStyleProperty(range, context, property, important, ruleType, result);
        break;
    }

    if (!parseSuccess)
        parsedProperties.shrink(initialParsedPropertiesSize);

    return parseSuccess;
}

RefPtr<CSSValue> CSSPropertyParser::parseStylePropertyLonghand(CSSPropertyID property, const String& string, const CSSParserContext& context)
{
    ASSERT(!WebCore::isShorthand(property));

    if (string.isEmpty())
        return nullptr;

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::Style,
        .currentProperty = property,
        .important = IsImportant::No,
    };
    if (RefPtr value = CSSParserFastPaths::maybeParseValue(property, string, state))
        return value;

    CSSTokenizer tokenizer(string);

    auto range = tokenizer.tokenRange();
    range.consumeWhitespace();

    if (RefPtr value = consumeCSSWideKeywordValue(range))
        return value;

    RefPtr value = CSSPropertyParsing::parseStylePropertyLonghand(range, property, state);
    if (!value || !range.atEnd())
        return nullptr;

    return value;
}

RefPtr<CSSValue> CSSPropertyParser::parseStylePropertyLonghand(CSSPropertyID property, CSSParserTokenRange range, const CSSParserContext& context)
{
    ASSERT(!WebCore::isShorthand(property));

    range.consumeWhitespace();

    if (RefPtr value = consumeCSSWideKeywordValue(range))
        return value;

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::Style,
        .currentProperty = property,
        .important = IsImportant::No,
    };

    RefPtr value = CSSPropertyParsing::parseStylePropertyLonghand(range, property, state);
    if (!value || !range.atEnd())
        return nullptr;

    return value;
}

RefPtr<CSSValue> CSSPropertyParser::parseCounterStyleDescriptor(CSSPropertyID property, const String& string, const CSSParserContext& context)
{
    auto tokenizer = CSSTokenizer(string);
    auto range = tokenizer.tokenRange();

    // Handle leading whitespace.
    range.consumeWhitespace();

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::CounterStyle,
        .currentProperty = property,
        .important = IsImportant::No,
    };

    auto result = CSSPropertyParsing::parseCounterStyleDescriptor(range, property, state);

    // Handle trailing whitespace.
    range.consumeWhitespace();

    if (!range.atEnd())
        return nullptr;

    return result;
}



// MARK: - Custom properties

std::optional<Variant<Ref<const Style::CustomProperty>, CSSWideKeyword>> CSSPropertyParser::parseTypedCustomPropertyValue(const AtomString& name, const CSSCustomPropertySyntax& syntax, CSSParserTokenRange range, Style::BuilderState& builderState, const CSSParserContext& context)
{
    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::Style,
        .currentProperty = CSSPropertyCustom,
        .important = IsImportant::No,
    };

    auto value = consumeTypedCustomPropertyValue(range, state, name, syntax, builderState);
    if (!value || !range.atEnd())
        return { };
    return value;
}

RefPtr<const Style::CustomProperty> CSSPropertyParser::parseTypedCustomPropertyInitialValue(const AtomString& name, const CSSCustomPropertySyntax& syntax, CSSParserTokenRange range, Style::BuilderState& builderState, const CSSParserContext& context)
{
    if (syntax.isUniversal())
        return CSSVariableParser::parseInitialValueForUniversalSyntax(name, range);

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::Style,
        .currentProperty = CSSPropertyCustom,
        .important = IsImportant::No,
    };

    auto value = consumeTypedCustomPropertyValue(range, state, name, syntax, builderState);
    if (!value || !range.atEnd())
        return { };

    return WTF::switchOn(*value,
        [](const Ref<const Style::CustomProperty>& resolved) -> RefPtr<const Style::CustomProperty> {
            return resolved.copyRef();
        },
        [](const CSSWideKeyword&) -> RefPtr<const Style::CustomProperty> {
            return nullptr;
        }
    );
}

ComputedStyleDependencies CSSPropertyParser::collectParsedCustomPropertyValueDependencies(const CSSCustomPropertySyntax& syntax, CSSParserTokenRange range, const CSSParserContext& context)
{
    if (syntax.isUniversal())
        return { };

    range.consumeWhitespace();

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::Style,
        .currentProperty = CSSPropertyCustom,
        .important = IsImportant::No,
    };

    auto [value, syntaxType] = consumeCustomPropertyValueWithSyntax(range, state, syntax);
    if (!value)
        return { };

    return value->computedStyleDependencies();
}

bool CSSPropertyParser::isValidCustomPropertyValueForSyntax(const CSSCustomPropertySyntax& syntax, CSSParserTokenRange range, const CSSParserContext& context)
{
    if (syntax.isUniversal())
        return true;

    range.consumeWhitespace();

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::Style,
        .currentProperty = CSSPropertyCustom,
        .important = IsImportant::No,
    };

    return !!consumeCustomPropertyValueWithSyntax(range, state, syntax).first;
}

std::optional<CSSWideKeyword> CSSPropertyParser::parseCSSWideKeyword(CSSParserTokenRange range)
{
    return consumeCSSWideKeyword(range);
}

std::pair<RefPtr<CSSValue>, CSSCustomPropertySyntax::Type> consumeCustomPropertyValueWithSyntax(CSSParserTokenRange& range, CSS::PropertyParserState& state, const CSSCustomPropertySyntax& syntax)
{
    ASSERT(!syntax.isUniversal());

    auto rangeCopy = range;

    auto consumeSingleValue = [&](auto& range, auto& component) -> RefPtr<CSSValue> {
        switch (component.type) {
        case CSSCustomPropertySyntax::Type::Length:
            return CSSPrimitiveValueResolver<CSS::Length<>>::consumeAndResolve(range, state);
        case CSSCustomPropertySyntax::Type::LengthPercentage:
            return CSSPrimitiveValueResolver<CSS::LengthPercentage<>>::consumeAndResolve(range, state);
        case CSSCustomPropertySyntax::Type::CustomIdent:
            if (RefPtr value = consumeCustomIdent(range)) {
                if (component.ident.isNull() || value->stringValue() == component.ident)
                    return value;
            }
            return nullptr;
        case CSSCustomPropertySyntax::Type::Percentage:
            return CSSPrimitiveValueResolver<CSS::Percentage<>>::consumeAndResolve(range, state);
        case CSSCustomPropertySyntax::Type::Integer:
            return CSSPrimitiveValueResolver<CSS::Integer<>>::consumeAndResolve(range, state);
        case CSSCustomPropertySyntax::Type::Number:
            return CSSPrimitiveValueResolver<CSS::Number<>>::consumeAndResolve(range, state);
        case CSSCustomPropertySyntax::Type::Angle:
            return CSSPrimitiveValueResolver<CSS::Angle<>>::consumeAndResolve(range, state);
        case CSSCustomPropertySyntax::Type::Time:
            return CSSPrimitiveValueResolver<CSS::Time<>>::consumeAndResolve(range, state);
        case CSSCustomPropertySyntax::Type::Resolution:
            return CSSPrimitiveValueResolver<CSS::Resolution<>>::consumeAndResolve(range, state);
        case CSSCustomPropertySyntax::Type::Color:
            return consumeColor(range, state);
        case CSSCustomPropertySyntax::Type::Image:
            return consumeImage(range, state, { AllowedImageType::URLFunction, AllowedImageType::GeneratedImage });
        case CSSCustomPropertySyntax::Type::URL:
            return consumeURL(range, state, { });
        case CSSCustomPropertySyntax::Type::String:
            return consumeString(range);
        case CSSCustomPropertySyntax::Type::TransformFunction:
            return CSSPropertyParsing::consumeTransformFunction(range, state);
        case CSSCustomPropertySyntax::Type::TransformList:
            return CSSPropertyParsing::consumeTransformList(range, state);
        case CSSCustomPropertySyntax::Type::Unknown:
            return nullptr;
        }
        ASSERT_NOT_REACHED();
        return nullptr;
    };

    auto consumeComponent = [&](auto& range, const auto& component) -> RefPtr<CSSValue> {
        switch (component.multiplier) {
        case CSSCustomPropertySyntax::Multiplier::Single:
            return consumeSingleValue(range, component);
        case CSSCustomPropertySyntax::Multiplier::CommaList:
            return consumeListSeparatedBy<',', OneOrMore>(range, [&](auto& range) {
                return consumeSingleValue(range, component);
            });
        case CSSCustomPropertySyntax::Multiplier::SpaceList:
            return consumeListSeparatedBy<' ', OneOrMore>(range, [&](auto& range) {
                return consumeSingleValue(range, component);
            });
        }
        ASSERT_NOT_REACHED();
        return nullptr;
    };

    for (auto& component : syntax.definition) {
        if (RefPtr value = consumeComponent(range, component)) {
            if (range.atEnd())
                return { value, component.type };
        }
        range = rangeCopy;
    }
    return { nullptr, CSSCustomPropertySyntax::Type::Unknown };
}

std::optional<Variant<Ref<const Style::CustomProperty>, CSSWideKeyword>> consumeTypedCustomPropertyValue(CSSParserTokenRange& range, CSS::PropertyParserState& state, const AtomString& name, const CSSCustomPropertySyntax& syntax, Style::BuilderState& builderState)
{
    if (syntax.isUniversal())
        return { { Style::CustomProperty::createForVariableData(name, CSSVariableData::create(range.consumeAll())) } };

    range.consumeWhitespace();

    if (auto keyword = consumeCSSWideKeyword(range))
        return { { *keyword } };

    auto [value, syntaxType] = consumeCustomPropertyValueWithSyntax(range, state, syntax);
    if (!value)
        return { };

    auto resolveSyntaxValue = [&, syntaxType = syntaxType](const CSSValue& value) -> std::optional<Style::CustomProperty::Value> {
        switch (syntaxType) {
        case CSSCustomPropertySyntax::Type::LengthPercentage:
        case CSSCustomPropertySyntax::Type::Length: {
            auto length = Style::BuilderConverter::convertLength(builderState, downcast<CSSPrimitiveValue>(value));
            return { WTFMove(length) };
        }
        case CSSCustomPropertySyntax::Type::Integer:
        case CSSCustomPropertySyntax::Type::Number: {
            auto doubleValue = downcast<CSSPrimitiveValue>(value).resolveAsNumber(builderState.cssToLengthConversionData());
            return { Style::CustomProperty::Numeric { doubleValue, CSSUnitType::CSS_NUMBER } };
        }
        case CSSCustomPropertySyntax::Type::Percentage: {
            auto doubleValue = downcast<CSSPrimitiveValue>(value).resolveAsPercentage(builderState.cssToLengthConversionData());
            return { Style::CustomProperty::Numeric { doubleValue, CSSUnitType::CSS_PERCENTAGE } };
        }
        case CSSCustomPropertySyntax::Type::Angle: {
            auto doubleValue = downcast<CSSPrimitiveValue>(value).resolveAsAngle(builderState.cssToLengthConversionData());
            return { Style::CustomProperty::Numeric { doubleValue, CSSUnitType::CSS_DEG } };
        }
        case CSSCustomPropertySyntax::Type::Time: {
            auto doubleValue = downcast<CSSPrimitiveValue>(value).resolveAsTime(builderState.cssToLengthConversionData());
            return { Style::CustomProperty::Numeric { doubleValue, CSSUnitType::CSS_S } };
        }
        case CSSCustomPropertySyntax::Type::Resolution: {
            auto doubleValue = downcast<CSSPrimitiveValue>(value).resolveAsResolution(builderState.cssToLengthConversionData());
            return { Style::CustomProperty::Numeric { doubleValue, CSSUnitType::CSS_DPPX } };
        }
        case CSSCustomPropertySyntax::Type::Color:
            return { Style::toStyleFromCSSValue<Style::Color>(builderState, value, Style::ForVisitedLink::No) };
        case CSSCustomPropertySyntax::Type::Image: {
            auto styleImage = builderState.createStyleImage(value);
            if (!styleImage)
                return { };
            return { WTFMove(styleImage) };
        }
        case CSSCustomPropertySyntax::Type::URL:
            return { Style::toStyle(downcast<CSSURLValue>(value).url(), builderState) };
        case CSSCustomPropertySyntax::Type::CustomIdent:
            return { CustomIdentifier { AtomString { downcast<CSSPrimitiveValue>(value).stringValue() } } };
        case CSSCustomPropertySyntax::Type::String:
            return { downcast<CSSPrimitiveValue>(value).stringValue() };
        case CSSCustomPropertySyntax::Type::TransformFunction:
        case CSSCustomPropertySyntax::Type::TransformList: {
            auto operation = Style::createTransformOperation(value, builderState);
            if (!operation)
                return { };
            return { Style::CustomProperty::Transform { *operation } };
        }
        case CSSCustomPropertySyntax::Type::Unknown:
            return { };
        }
        ASSERT_NOT_REACHED();
        return { };
    };

    if (is<CSSValueList>(value.get()) || is<CSSTransformListValue>(value.get())) {
        Ref valueList = downcast<CSSValueContainingVector>(value.releaseNonNull());
        auto syntaxValueList = Style::CustomProperty::ValueList { { }, valueList->separator() };
        for (Ref listValue : valueList.get()) {
            auto syntaxValue = resolveSyntaxValue(listValue);
            if (!syntaxValue)
                return { };
            syntaxValueList.values.append(WTFMove(*syntaxValue));
        }
        return { { Style::CustomProperty::createForValueList(name, WTFMove(syntaxValueList)) } };
    };

    auto syntaxValue = resolveSyntaxValue(*value);
    if (!syntaxValue)
        return { };

    return { { Style::CustomProperty::createForValue(name, WTFMove(*syntaxValue)) } };
}

// MARK: - Root consumers

bool consumeStyleProperty(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, IsImportant important, StyleRuleType ruleType, CSS::PropertyParserResult& result)
{
    if (CSSProperty::isDescriptorOnly(property))
        return false;

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = ruleType,
        .currentProperty = property,
        .important = important,
    };

    if (WebCore::isShorthand(property)) {
        auto rangeCopy = range;
        if (RefPtr keywordValue = consumeCSSWideKeywordValue(rangeCopy)) {
            result.addPropertyForAllLonghandsOfCurrentShorthand(state, WTFMove(keywordValue));
            range = rangeCopy;
            return true;
        }

        auto originalRange = range;

        if (CSSPropertyParsing::parseStylePropertyShorthand(range, property, state, result))
            return true;

        if (CSSVariableParser::containsValidVariableReferences(originalRange, context)) {
            result.addPropertyForAllLonghandsOfCurrentShorthand(state, CSSPendingSubstitutionValue::create(property, CSSVariableReferenceValue::create(originalRange, context)));
            return true;
        }
    } else {
        auto rangeCopy = range;
        if (RefPtr keywordValue = consumeCSSWideKeywordValue(rangeCopy)) {
            result.addProperty(state, property, CSSPropertyInvalid, WTFMove(keywordValue), important);
            range = rangeCopy;
            return true;
        }

        auto originalRange = range;

        RefPtr parsedValue = CSSPropertyParsing::parseStylePropertyLonghand(range, property, state);
        if (parsedValue && range.atEnd()) {
            result.addProperty(state, property, CSSPropertyInvalid, WTFMove(parsedValue), important);
            return true;
        }

        if (CSSVariableParser::containsValidVariableReferences(originalRange, context)) {
            result.addProperty(state, property, CSSPropertyInvalid, CSSVariableReferenceValue::create(originalRange, context), important);
            return true;
        }
    }

    return false;
}

bool consumeFontFaceDescriptor(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, CSS::PropertyParserResult& result)
{
    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::FontFace,
        .currentProperty = property,
        .important = IsImportant::No,
    };

    RefPtr parsedValue = CSSPropertyParsing::parseFontFaceDescriptor(range, property, state);
    if (!parsedValue || !range.atEnd())
        return false;

    result.addProperty(state, property, CSSPropertyInvalid, WTFMove(parsedValue), IsImportant::No);
    return true;
}

bool consumeFontPaletteValuesDescriptor(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, CSS::PropertyParserResult& result)
{
    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::FontPaletteValues,
        .currentProperty = property,
        .important = IsImportant::No,
    };

    RefPtr parsedValue = CSSPropertyParsing::parseFontPaletteValuesDescriptor(range, property, state);
    if (!parsedValue || !range.atEnd())
        return false;

    result.addProperty(state, property, CSSPropertyInvalid, WTFMove(parsedValue), IsImportant::No);
    return true;
}

bool consumeCounterStyleDescriptor(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, CSS::PropertyParserResult& result)
{
    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::CounterStyle,
        .currentProperty = property,
        .important = IsImportant::No,
    };

    RefPtr parsedValue = CSSPropertyParsing::parseCounterStyleDescriptor(range, property, state);
    if (!parsedValue || !range.atEnd())
        return false;

    result.addProperty(state, property, CSSPropertyInvalid, WTFMove(parsedValue), IsImportant::No);
    return true;
}

bool consumeKeyframeDescriptor(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, IsImportant important, CSS::PropertyParserResult& result)
{
    // https://www.w3.org/TR/css-animations-1/#keyframes
    // The <declaration-list> inside of <keyframe-block> accepts any CSS property except those
    // defined in this specification, but does accept the animation-timing-function property and
    // interprets it specially.
    switch (property) {
    case CSSPropertyAnimation:
    case CSSPropertyAnimationDelay:
    case CSSPropertyAnimationDirection:
    case CSSPropertyAnimationDuration:
    case CSSPropertyAnimationFillMode:
    case CSSPropertyAnimationIterationCount:
    case CSSPropertyAnimationName:
    case CSSPropertyAnimationPlayState:
        return false;
    default:
        return consumeStyleProperty(range, context, property, important, StyleRuleType::Keyframe, result);
    }
}

bool consumePageDescriptor(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, IsImportant important, CSS::PropertyParserResult& result)
{
    // Does not apply in @page per-spec.
    if (property == CSSPropertyPage)
        return false;

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::Page,
        .currentProperty = property,
        .important = IsImportant::No,
    };

    if (RefPtr parsedValue = CSSPropertyParsing::parsePageDescriptor(range, property, state)) {
        if (!range.atEnd())
            return false;

        result.addProperty(state, property, CSSPropertyInvalid, WTFMove(parsedValue), IsImportant::No);
        return true;
    }

    return consumeStyleProperty(range, context, property, important, StyleRuleType::Page, result);
}

bool consumePropertyDescriptor(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, CSS::PropertyParserResult& result)
{
    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::Property,
        .currentProperty = property,
        .important = IsImportant::No,
    };

    RefPtr parsedValue = CSSPropertyParsing::parsePropertyDescriptor(range, property, state);
    if (!parsedValue || !range.atEnd())
        return false;

    result.addProperty(state, property, CSSPropertyInvalid, WTFMove(parsedValue), IsImportant::No);
    return true;
}

bool consumeViewTransitionDescriptor(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, CSS::PropertyParserResult& result)
{
    ASSERT(context.propertySettings.crossDocumentViewTransitionsEnabled);

    auto state = CSS::PropertyParserState {
        .context = context,
        .currentRule = StyleRuleType::ViewTransition,
        .currentProperty = property,
        .important = IsImportant::No,
    };

    RefPtr parsedValue = CSSPropertyParsing::parseViewTransitionDescriptor(range, property, state);
    if (!parsedValue || !range.atEnd())
        return false;

    result.addProperty(state, property, CSSPropertyInvalid, WTFMove(parsedValue), IsImportant::No);
    return true;
}

// Checks whether a CSS property is allowed in @position-try.
static bool propertyAllowedInPositionTryRule(CSSPropertyID property)
{
    return CSSProperty::isInsetProperty(property)
        || CSSProperty::isMarginProperty(property)
        || CSSProperty::isSizingProperty(property)
        || property == CSSPropertyAlignSelf
        || property == CSSPropertyJustifySelf
        || property == CSSPropertyPlaceSelf
        || property == CSSPropertyPositionAnchor
        || property == CSSPropertyPositionArea;
}

bool consumePositionTryDescriptor(CSSParserTokenRange& range, const CSSParserContext& context, CSSPropertyID property, IsImportant important, CSS::PropertyParserResult& result)
{
    ASSERT(context.propertySettings.cssAnchorPositioningEnabled);

    // Per spec, !important is not allowed and makes the whole declaration invalid.
    if (important == IsImportant::Yes)
        return false;

    if (!propertyAllowedInPositionTryRule(property))
        return false;

    return consumeStyleProperty(range, context, property, important, StyleRuleType::PositionTry, result);
}

} // namespace WebCore