Serenity Operating System
1/*
2 * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#pragma once
8
9#include <AK/String.h>
10
11namespace Web::CSS {
12
13// Corresponds to Kleene 3-valued logic.
14// https://www.w3.org/TR/mediaqueries-4/#evaluating
15enum class MatchResult {
16 False,
17 True,
18 Unknown,
19};
20
21inline MatchResult as_match_result(bool value)
22{
23 return value ? MatchResult::True : MatchResult::False;
24}
25
26inline MatchResult negate(MatchResult value)
27{
28 switch (value) {
29 case MatchResult::False:
30 return MatchResult::True;
31 case MatchResult::True:
32 return MatchResult::False;
33 case MatchResult::Unknown:
34 return MatchResult::Unknown;
35 }
36 VERIFY_NOT_REACHED();
37}
38
39template<typename Collection, typename Evaluate>
40inline MatchResult evaluate_and(Collection& collection, Evaluate evaluate)
41{
42 size_t true_results = 0;
43 for (auto& item : collection) {
44 auto item_match = evaluate(item);
45 if (item_match == MatchResult::False)
46 return MatchResult::False;
47 if (item_match == MatchResult::True)
48 true_results++;
49 }
50 if (true_results == collection.size())
51 return MatchResult::True;
52 return MatchResult::Unknown;
53}
54
55template<typename Collection, typename Evaluate>
56inline MatchResult evaluate_or(Collection& collection, Evaluate evaluate)
57{
58 size_t false_results = 0;
59 for (auto& item : collection) {
60 auto item_match = evaluate(item);
61 if (item_match == MatchResult::True)
62 return MatchResult::True;
63 if (item_match == MatchResult::False)
64 false_results++;
65 }
66 if (false_results == collection.size())
67 return MatchResult::False;
68 return MatchResult::Unknown;
69}
70
71// https://www.w3.org/TR/mediaqueries-4/#typedef-general-enclosed
72class GeneralEnclosed {
73public:
74 GeneralEnclosed(String serialized_contents)
75 : m_serialized_contents(move(serialized_contents))
76 {
77 }
78
79 MatchResult evaluate() const { return MatchResult::Unknown; }
80 String const& to_string() const { return m_serialized_contents; }
81
82private:
83 String m_serialized_contents;
84};
85}