summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/css/css_math_expression_node.h
blob: 624e5d70ac5388ebc3eeb8743f400d59b39da33e (plain)
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
/*
 * Copyright (C) 2011, 2012 Google Inc. All rights reserved.
 *
 * 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.
 */

#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_EXPRESSION_NODE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_EXPRESSION_NODE_H_

#include "base/dcheck_is_on.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/css/css_math_operator.h"
#include "third_party/blink/renderer/core/css/css_primitive_value.h"
#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h"
#include "third_party/blink/renderer/platform/geometry/calculation_value.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"

namespace blink {

static const int kMaxExpressionDepth = 100;

class CalculationExpressionNode;
class CSSNumericLiteralValue;

// The order of this enum should not change since its elements are used as
// indices in the addSubtractResult matrix.
enum CalculationCategory {
  kCalcNumber,
  kCalcLength,
  kCalcPercent,
  kCalcPercentLength,
  kCalcAngle,
  kCalcTime,
  kCalcFrequency,
  kCalcOther,
};

class CORE_EXPORT CSSMathExpressionNode
    : public GarbageCollected<CSSMathExpressionNode> {
 public:
  static CSSMathExpressionNode* Create(const CalculationValue& node);
  static CSSMathExpressionNode* Create(PixelsAndPercent pixels_and_percent);
  static CSSMathExpressionNode* Create(const CalculationExpressionNode& node);

  static CSSMathExpressionNode* ParseCalc(const CSSParserTokenRange& tokens);
  static CSSMathExpressionNode* ParseMin(const CSSParserTokenRange& tokens);
  static CSSMathExpressionNode* ParseMax(const CSSParserTokenRange& tokens);
  static CSSMathExpressionNode* ParseClamp(const CSSParserTokenRange& tokens);

  virtual bool IsNumericLiteral() const { return false; }
  virtual bool IsBinaryOperation() const { return false; }
  virtual bool IsVariadicOperation() const { return false; }

  bool IsMathFunction() const {
    return !IsNumericLiteral() && !IsBinaryOperation();
  }

  virtual bool IsZero() const = 0;

  // Resolves the expression into one value *without doing any type conversion*.
  // Hits DCHECK if type conversion is required.
  virtual double DoubleValue() const = 0;

  virtual double ComputeLengthPx(const CSSToLengthConversionData&) const = 0;
  virtual bool AccumulateLengthArray(CSSLengthArray&,
                                     double multiplier) const = 0;
  virtual void AccumulateLengthUnitTypes(
      CSSPrimitiveValue::LengthTypeFlags& types) const = 0;
  virtual scoped_refptr<const CalculationExpressionNode>
  ToCalculationExpression(const CSSToLengthConversionData&) const = 0;
  virtual absl::optional<PixelsAndPercent> ToPixelsAndPercent(
      const CSSToLengthConversionData&) const = 0;

  scoped_refptr<const CalculationValue> ToCalcValue(
      const CSSToLengthConversionData& conversion_data,
      ValueRange range,
      bool allows_negative_percentage_reference) const;

  // Evaluates the expression with type conversion (e.g., cm -> px) handled, and
  // returns the result value in the canonical unit of the corresponding
  // category (see https://www.w3.org/TR/css3-values/#canonical-unit).
  // TODO(crbug.com/984372): We currently use 'ms' as the canonical unit of
  // <time>. Switch to 's' to follow the spec.
  // Returns |nullopt| on evaluation failures due to the following reasons:
  // - The category doesn't have a canonical unit (e.g., |kCalcPercentLength|).
  // - A type conversion that doesn't have a fixed conversion ratio is needed
  //   (e.g., between 'px' and 'em').
  // - There's an unsupported calculation, e.g., dividing two lengths.
  virtual absl::optional<double> ComputeValueInCanonicalUnit() const = 0;

  virtual String CustomCSSText() const = 0;
  virtual bool operator==(const CSSMathExpressionNode& other) const {
    return category_ == other.category_ && is_integer_ == other.is_integer_;
  }

  virtual bool IsComputationallyIndependent() const = 0;

  CalculationCategory Category() const { return category_; }
  bool HasPercentage() const {
    return category_ == kCalcPercent || category_ == kCalcPercentLength;
  }

  // Returns the unit type of the math expression *without doing any type
  // conversion* (e.g., 1px + 1em needs type conversion to resolve).
  // Returns |UnitType::kUnknown| if type conversion is required.
  virtual CSSPrimitiveValue::UnitType ResolvedUnitType() const = 0;

  bool IsInteger() const { return is_integer_; }

  bool IsNestedCalc() const { return is_nested_calc_; }
  void SetIsNestedCalc() { is_nested_calc_ = true; }

  bool HasComparisons() const { return has_comparisons_; }

#if DCHECK_IS_ON()
  // There's a subtle issue in comparing two percentages, e.g., min(10%, 20%).
  // It doesn't always resolve into 10%, because the reference value may be
  // negative. We use this to prevent comparing two percentages without knowing
  // the sign of the reference value.
  virtual bool InvolvesPercentageComparisons() const = 0;
#endif

  virtual void Trace(Visitor* visitor) const {}

 protected:
  CSSMathExpressionNode(CalculationCategory category,
                        bool is_integer,
                        bool has_comparisons)
      : category_(category),
        is_integer_(is_integer),
        has_comparisons_(has_comparisons) {
    DCHECK_NE(category, kCalcOther);
  }

  CalculationCategory category_;
  bool is_integer_;
  bool is_nested_calc_ = false;
  bool has_comparisons_;
};

class CORE_EXPORT CSSMathExpressionNumericLiteral final
    : public CSSMathExpressionNode {
 public:
  static CSSMathExpressionNumericLiteral* Create(
      const CSSNumericLiteralValue* value,
      bool is_integer = false);
  static CSSMathExpressionNumericLiteral*
  Create(double value, CSSPrimitiveValue::UnitType type, bool is_integer);

  CSSMathExpressionNumericLiteral(const CSSNumericLiteralValue* value,
                                  bool is_integer);

  const CSSNumericLiteralValue& GetValue() const { return *value_; }

  bool IsNumericLiteral() const final { return true; }

  bool IsZero() const final;
  String CustomCSSText() const final;
  scoped_refptr<const CalculationExpressionNode> ToCalculationExpression(
      const CSSToLengthConversionData&) const final;
  absl::optional<PixelsAndPercent> ToPixelsAndPercent(
      const CSSToLengthConversionData&) const final;
  double DoubleValue() const final;
  absl::optional<double> ComputeValueInCanonicalUnit() const final;
  double ComputeLengthPx(
      const CSSToLengthConversionData& conversion_data) const final;
  bool AccumulateLengthArray(CSSLengthArray& length_array,
                             double multiplier) const final;
  void AccumulateLengthUnitTypes(
      CSSPrimitiveValue::LengthTypeFlags& types) const final;
  bool IsComputationallyIndependent() const final;
  bool operator==(const CSSMathExpressionNode& other) const final;
  CSSPrimitiveValue::UnitType ResolvedUnitType() const final;
  void Trace(Visitor* visitor) const final;

#if DCHECK_IS_ON()
  bool InvolvesPercentageComparisons() const final;
#endif

 private:
  Member<const CSSNumericLiteralValue> value_;
};

template <>
struct DowncastTraits<CSSMathExpressionNumericLiteral> {
  static bool AllowFrom(const CSSMathExpressionNode& node) {
    return node.IsNumericLiteral();
  }
};

class CORE_EXPORT CSSMathExpressionBinaryOperation final
    : public CSSMathExpressionNode {
 public:
  static CSSMathExpressionNode* Create(const CSSMathExpressionNode* left_side,
                                       const CSSMathExpressionNode* right_side,
                                       CSSMathOperator op);
  static CSSMathExpressionNode* CreateSimplified(
      const CSSMathExpressionNode* left_side,
      const CSSMathExpressionNode* right_side,
      CSSMathOperator op);

  CSSMathExpressionBinaryOperation(const CSSMathExpressionNode* left_side,
                                   const CSSMathExpressionNode* right_side,
                                   CSSMathOperator op,
                                   CalculationCategory category);

  const CSSMathExpressionNode* LeftExpressionNode() const { return left_side_; }
  const CSSMathExpressionNode* RightExpressionNode() const {
    return right_side_;
  }
  CSSMathOperator OperatorType() const { return operator_; }

  bool IsBinaryOperation() const final { return true; }

  bool IsZero() const final;
  scoped_refptr<const CalculationExpressionNode> ToCalculationExpression(
      const CSSToLengthConversionData&) const final;
  absl::optional<PixelsAndPercent> ToPixelsAndPercent(
      const CSSToLengthConversionData&) const final;
  double DoubleValue() const final;
  absl::optional<double> ComputeValueInCanonicalUnit() const final;
  double ComputeLengthPx(
      const CSSToLengthConversionData& conversion_data) const final;
  bool AccumulateLengthArray(CSSLengthArray& length_array,
                             double multiplier) const final;
  void AccumulateLengthUnitTypes(
      CSSPrimitiveValue::LengthTypeFlags& types) const final;
  bool IsComputationallyIndependent() const final;
  String CustomCSSText() const final;
  bool operator==(const CSSMathExpressionNode& exp) const final;
  CSSPrimitiveValue::UnitType ResolvedUnitType() const final;
  void Trace(Visitor* visitor) const final;

#if DCHECK_IS_ON()
  bool InvolvesPercentageComparisons() const final;
#endif

 private:
  static const CSSMathExpressionNode* GetNumberSide(
      const CSSMathExpressionNode* left_side,
      const CSSMathExpressionNode* right_side);

  double Evaluate(double left_side, double right_side) const {
    return EvaluateOperator(left_side, right_side, operator_);
  }

  static double EvaluateOperator(double left_value,
                                 double right_value,
                                 CSSMathOperator op);

  const Member<const CSSMathExpressionNode> left_side_;
  const Member<const CSSMathExpressionNode> right_side_;
  const CSSMathOperator operator_;
};

template <>
struct DowncastTraits<CSSMathExpressionBinaryOperation> {
  static bool AllowFrom(const CSSMathExpressionNode& node) {
    return node.IsBinaryOperation();
  }
};

class CSSMathExpressionVariadicOperation final : public CSSMathExpressionNode {
 public:
  using Operands = HeapVector<Member<const CSSMathExpressionNode>>;

  static CSSMathExpressionVariadicOperation* Create(Operands&& operands,
                                                    CSSMathOperator op);

  CSSMathExpressionVariadicOperation(CalculationCategory category,
                                     bool is_integer_result,
                                     Operands&& operands,
                                     CSSMathOperator op);

  const Operands& GetOperands() const { return operands_; }
  CSSMathOperator OperatorType() const { return operator_; }

  bool IsVariadicOperation() const final { return true; }

  void SetIsClamp() { is_clamp_ = true; }
  String CSSTextAsClamp() const;

  bool IsZero() const final;
  String CustomCSSText() const final;
  scoped_refptr<const CalculationExpressionNode> ToCalculationExpression(
      const CSSToLengthConversionData&) const final;
  absl::optional<PixelsAndPercent> ToPixelsAndPercent(
      const CSSToLengthConversionData&) const final;
  double DoubleValue() const final;
  double ComputeLengthPx(
      const CSSToLengthConversionData& conversion_data) const final;
  bool AccumulateLengthArray(CSSLengthArray& length_array,
                             double multiplier) const final;
  void AccumulateLengthUnitTypes(
      CSSPrimitiveValue::LengthTypeFlags& types) const final;
  absl::optional<double> ComputeValueInCanonicalUnit() const final;
  bool IsComputationallyIndependent() const final;
  bool operator==(const CSSMathExpressionNode& other) const final;
  CSSPrimitiveValue::UnitType ResolvedUnitType() const final;
  void Trace(Visitor* visitor) const final;

#if DCHECK_IS_ON()
  bool InvolvesPercentageComparisons() const final;
#endif

 private:
  // Helper for iterating from the 2nd to the last operands
  base::span<const Member<const CSSMathExpressionNode>> SecondToLastOperands()
      const {
    return base::make_span(std::next(operands_.begin()), operands_.end());
  }

  double EvaluateBinary(double lhs, double rhs) const;

  Operands operands_;
  const CSSMathOperator operator_;
  bool is_clamp_ = false;
};

template <>
struct DowncastTraits<CSSMathExpressionVariadicOperation> {
  static bool AllowFrom(const CSSMathExpressionNode& node) {
    return node.IsVariadicOperation();
  }
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_MATH_EXPRESSION_NODE_H_