/
calculation.dart
406 lines (347 loc) · 13.6 KB
/
calculation.dart
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
// Copyright 2021 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:meta/meta.dart';
import '../exception.dart';
import '../util/nullable.dart';
import '../util/number.dart';
import '../utils.dart';
import '../value.dart';
import '../visitor/interface/value.dart';
import '../visitor/serialize.dart';
/// A SassScript calculation.
///
/// Although calculations can in principle have any name or any number of
/// arguments, this class only exposes the specific calculations that are
/// supported by the Sass spec. This ensures that all calculations that the user
/// works with are always fully simplified.
///
/// {@category Value}
@sealed
class SassCalculation extends Value {
/// The calculation's name, such as `"calc"`.
final String name;
/// The calculation's arguments.
///
/// Each argument is either a [SassNumber], a [SassCalculation], an unquoted
/// [SassString], a [CalculationOperation], or a [CalculationInterpolation].
final List<Object> arguments;
/// @nodoc
@internal
bool get isSpecialNumber => true;
/// Creates a `calc()` calculation with the given [argument].
///
/// The [argument] must be either a [SassNumber], a [SassCalculation], an
/// unquoted [SassString], a [CalculationOperation], or a
/// [CalculationInterpolation].
///
/// This automatically simplifies the calculation, so it may return a
/// [SassNumber] rather than a [SassCalculation]. It throws an exception if it
/// can determine that the calculation will definitely produce invalid CSS.
static Value calc(Object argument) {
argument = _simplify(argument);
if (argument is SassNumber) return argument;
if (argument is SassCalculation) return argument;
return SassCalculation._("calc", List.unmodifiable([argument]));
}
/// Creates a `min()` calculation with the given [arguments].
///
/// Each argument must be either a [SassNumber], a [SassCalculation], an
/// unquoted [SassString], a [CalculationOperation], or a
/// [CalculationInterpolation]. It must be passed at least one argument.
///
/// This automatically simplifies the calculation, so it may return a
/// [SassNumber] rather than a [SassCalculation]. It throws an exception if it
/// can determine that the calculation will definitely produce invalid CSS.
static Value min(Iterable<Object> arguments) {
var args = _simplifyArguments(arguments);
if (args.isEmpty) {
throw ArgumentError("min() must have at least one argument.");
}
SassNumber? minimum;
for (var arg in args) {
if (arg is! SassNumber ||
(minimum != null && !minimum.isComparableTo(arg))) {
minimum = null;
break;
} else if (minimum == null || minimum.greaterThan(arg).isTruthy) {
minimum = arg;
}
}
if (minimum != null) return minimum;
_verifyCompatibleNumbers(args);
return SassCalculation._("min", args);
}
/// Creates a `max()` calculation with the given [arguments].
///
/// Each argument must be either a [SassNumber], a [SassCalculation], an
/// unquoted [SassString], a [CalculationOperation], or a
/// [CalculationInterpolation]. It must be passed at least one argument.
///
/// This automatically simplifies the calculation, so it may return a
/// [SassNumber] rather than a [SassCalculation]. It throws an exception if it
/// can determine that the calculation will definitely produce invalid CSS.
static Value max(Iterable<Object> arguments) {
var args = _simplifyArguments(arguments);
if (args.isEmpty) {
throw ArgumentError("max() must have at least one argument.");
}
SassNumber? maximum;
for (var arg in args) {
if (arg is! SassNumber ||
(maximum != null && !maximum.isComparableTo(arg))) {
maximum = null;
break;
} else if (maximum == null || maximum.lessThan(arg).isTruthy) {
maximum = arg;
}
}
if (maximum != null) return maximum;
_verifyCompatibleNumbers(args);
return SassCalculation._("max", args);
}
/// Creates a `clamp()` calculation with the given [min], [value], and [max].
///
/// Each argument must be either a [SassNumber], a [SassCalculation], an
/// unquoted [SassString], a [CalculationOperation], or a
/// [CalculationInterpolation].
///
/// This automatically simplifies the calculation, so it may return a
/// [SassNumber] rather than a [SassCalculation]. It throws an exception if it
/// can determine that the calculation will definitely produce invalid CSS.
///
/// This may be passed fewer than three arguments, but only if one of the
/// arguments is an unquoted `var()` string.
static Value clamp(Object min, [Object? value, Object? max]) {
if (value == null && max != null) {
throw ArgumentError("If value is null, max must also be null.");
}
min = _simplify(min);
value = value.andThen(_simplify);
max = max.andThen(_simplify);
if (min is SassNumber &&
value is SassNumber &&
max is SassNumber &&
min.hasCompatibleUnits(value) &&
min.hasCompatibleUnits(max)) {
if (value.lessThanOrEquals(min).isTruthy) return min;
if (value.greaterThanOrEquals(max).isTruthy) return max;
return value;
}
var args = List<Object>.unmodifiable(
[min, if (value != null) value, if (max != null) max]);
_verifyCompatibleNumbers(args);
_verifyLength(args, 3);
return SassCalculation._("clamp", args);
}
/// Creates and simplifies a [CalculationOperation] with the given [operator],
/// [left], and [right].
///
/// This automatically simplifies the operation, so it may return a
/// [SassNumber] rather than a [CalculationOperation].
///
/// Each of [left] and [right] must be either a [SassNumber], a
/// [SassCalculation], an unquoted [SassString], a [CalculationOperation], or
/// a [CalculationInterpolation].
static Object operate(
CalculationOperator operator, Object left, Object right) =>
operateInternal(operator, left, right, inMinMax: false);
/// Like [operate], but with the internal-only [inMinMax] parameter.
///
/// If [inMinMax] is `true`, this allows unitless numbers to be added and
/// subtracted with numbers with units, for backwards-compatibility with the
/// old global `min()` and `max()` functions.
@internal
static Object operateInternal(
CalculationOperator operator, Object left, Object right,
{required bool inMinMax}) {
left = _simplify(left);
right = _simplify(right);
if (operator == CalculationOperator.plus ||
operator == CalculationOperator.minus) {
if (left is SassNumber &&
right is SassNumber &&
(inMinMax
? left.isComparableTo(right)
: left.hasCompatibleUnits(right))) {
return operator == CalculationOperator.plus
? left.plus(right)
: left.minus(right);
}
_verifyCompatibleNumbers([left, right]);
if (right is SassNumber && fuzzyLessThan(right.value, 0)) {
right = right.times(SassNumber(-1));
operator = operator == CalculationOperator.plus
? CalculationOperator.minus
: CalculationOperator.plus;
}
return CalculationOperation._(operator, left, right);
} else if (left is SassNumber && right is SassNumber) {
return operator == CalculationOperator.times
? left.times(right)
: left.dividedBy(right);
} else {
return CalculationOperation._(operator, left, right);
}
}
/// An internal constructor that doesn't perform any validation or
/// simplification.
SassCalculation._(this.name, this.arguments);
/// Returns an unmodifiable list of [args], with each argument simplified.
static List<Object> _simplifyArguments(Iterable<Object> args) =>
List.unmodifiable(args.map(_simplify));
/// Simplifies a calculation argument.
static Object _simplify(Object arg) {
if (arg is SassNumber ||
arg is CalculationInterpolation ||
arg is CalculationOperation) {
return arg;
} else if (arg is SassString) {
if (!arg.hasQuotes) return arg;
throw _exception("Quoted string $arg can't be used in a calculation.");
} else if (arg is SassCalculation) {
return arg.name == 'calc' ? arg.arguments[0] : arg;
} else if (arg is Value) {
throw _exception("Value $arg can't be used in a calculation.");
} else {
throw ArgumentError("Unexpected calculation argument $arg.");
}
}
/// Verifies that all the numbers in [args] aren't known to be incomaptible
/// with one another, and that they don't have units that are too complex for
/// calculations.
static void _verifyCompatibleNumbers(List<Object> args) {
// Note: this logic is largely duplicated in
// _EvaluateVisitor._verifyCompatibleNumbers and most changes here should
// also be reflected there.
for (var arg in args) {
if (arg is! SassNumber) continue;
if (arg.numeratorUnits.length > 1 || arg.denominatorUnits.isNotEmpty) {
throw _exception("Number $arg isn't compatible with CSS calculations.");
}
}
for (var i = 0; i < args.length - 1; i++) {
var number1 = args[i];
if (number1 is! SassNumber) continue;
for (var j = i + 1; j < args.length; j++) {
var number2 = args[j];
if (number2 is! SassNumber) continue;
if (number1.hasPossiblyCompatibleUnits(number2)) continue;
throw _exception("$number1 and $number2 are incompatible.");
}
}
}
/// Throws a [SassScriptException] if [args] isn't [expectedLength] *and*
/// doesn't contain either a [SassString] or a [CalculationInterpolation].
static void _verifyLength(List<Object> args, int expectedLength) {
if (args.length == expectedLength) return;
if (args
.any((arg) => arg is SassString || arg is CalculationInterpolation)) {
return;
}
throw _exception(
"$expectedLength arguments required, but only ${args.length} "
"${pluralize('was', args.length, plural: 'were')} passed.");
}
/// @nodoc
@internal
T accept<T>(ValueVisitor<T> visitor) => visitor.visitCalculation(this);
SassCalculation assertCalculation([String? name]) => this;
/// @nodoc
@internal
Value plus(Value other) {
if (other is SassString) return super.plus(other);
throw SassScriptException('Undefined operation "$this + $other".');
}
/// @nodoc
@internal
Value minus(Value other) =>
throw SassScriptException('Undefined operation "$this - $other".');
/// @nodoc
@internal
Value unaryPlus() =>
throw SassScriptException('Undefined operation "+$this".');
/// @nodoc
@internal
Value unaryMinus() =>
throw SassScriptException('Undefined operation "-$this".');
bool operator ==(Object other) =>
other is SassCalculation &&
name == other.name &&
listEquals(arguments, other.arguments);
int get hashCode => name.hashCode ^ listHash(arguments);
/// Throws a [SassScriptException] with the given [message].
static SassScriptException _exception(String message, [String? name]) =>
SassScriptException(name == null ? message : "\$$name: $message");
}
/// A binary operation that can appear in a [SassCalculation].
///
/// {@category Value}
@sealed
class CalculationOperation {
/// The operator.
final CalculationOperator operator;
/// The left-hand operand.
///
/// This is either a [SassNumber], a [SassCalculation], an unquoted
/// [SassString], a [CalculationOperation], or a [CalculationInterpolation].
final Object left;
/// The right-hand operand.
///
/// This is either a [SassNumber], a [SassCalculation], an unquoted
/// [SassString], a [CalculationOperation], or a [CalculationInterpolation].
final Object right;
CalculationOperation._(this.operator, this.left, this.right);
bool operator ==(Object other) =>
other is CalculationOperation &&
left == other.left &&
right == other.right;
int get hashCode => operator.hashCode ^ left.hashCode ^ right.hashCode;
String toString() {
var parenthesized =
serializeValue(SassCalculation._("", [this]), inspect: true);
return parenthesized.substring(1, parenthesized.length - 1);
}
}
/// An enumeration of possible operators for [CalculationOperation].
///
/// {@category Value}
@sealed
class CalculationOperator {
/// The addition operator.
static const plus = CalculationOperator._("plus", "+", 1);
/// The subtraction operator.
static const minus = CalculationOperator._("minus", "-", 1);
/// The multiplication operator.
static const times = CalculationOperator._("times", "*", 2);
/// The division operator.
static const dividedBy = CalculationOperator._("divided by", "/", 2);
/// The English name of [this].
final String name;
/// The CSS syntax for [this].
final String operator;
/// The precedence of [this].
///
/// An operator with higher precedence binds tighter.
///
/// @nodoc
@internal
final int precedence;
const CalculationOperator._(this.name, this.operator, this.precedence);
String toString() => name;
}
/// A string injected into a [SassCalculation] using interpolation.
///
/// This is tracked separately from string arguments because it requires
/// additional parentheses when used as an operand of a [CalculationOperation].
///
/// {@category Value}
@sealed
class CalculationInterpolation {
final String value;
CalculationInterpolation(this.value);
bool operator ==(Object other) =>
other is CalculationInterpolation && value == other.value;
int get hashCode => value.hashCode;
String toString() => value;
}