/
value.dart
486 lines (436 loc) · 16.3 KB
/
value.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
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
// Copyright 2016 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 'ast/selector.dart';
import 'exception.dart';
import 'utils.dart';
import 'value/boolean.dart';
import 'value/calculation.dart';
import 'value/color.dart';
import 'value/function.dart';
import 'value/list.dart';
import 'value/map.dart';
import 'value/number.dart';
import 'value/string.dart';
import 'visitor/interface/value.dart';
import 'visitor/serialize.dart';
export 'value/argument_list.dart';
export 'value/boolean.dart';
export 'value/calculation.dart';
export 'value/color.dart';
export 'value/function.dart';
export 'value/list.dart';
export 'value/map.dart';
export 'value/null.dart';
export 'value/number.dart' hide conversionFactor;
export 'value/string.dart';
/// A SassScript value.
///
/// All SassScript values are unmodifiable. New values can be constructed using
/// subclass constructors like [SassString.new]. Untyped values can be cast to
/// particular types using `assert*()` functions like [assertString], which
/// throw user-friendly error messages if they fail.
///
/// {@category Value}
@sealed
abstract class Value {
/// Whether the value counts as `true` in an `@if` statement and other
/// contexts.
bool get isTruthy => true;
/// The separator for this value as a list.
///
/// All SassScript values can be used as lists. Maps count as lists of pairs,
/// and all other values count as single-value lists.
ListSeparator get separator => ListSeparator.undecided;
/// Whether this value as a list has brackets.
///
/// All SassScript values can be used as lists. Maps count as lists of pairs,
/// and all other values count as single-value lists.
bool get hasBrackets => false;
/// This value as a list.
///
/// All SassScript values can be used as lists. Maps count as lists of pairs,
/// and all other values count as single-value lists.
List<Value> get asList => [this];
/// The length of [asList].
///
/// This is used to compute [sassIndexToListIndex] without allocating a new
/// list.
///
/// @nodoc
@protected
int get lengthAsList => 1;
/// Whether the value will be represented in CSS as the empty string.
///
/// @nodoc
@internal
bool get isBlank => false;
/// Whether this is a value that CSS may treat as a number, such as `calc()`
/// or `var()`.
///
/// Functions that shadow plain CSS functions need to gracefully handle when
/// these arguments are passed in.
///
/// @nodoc
@internal
bool get isSpecialNumber => false;
/// Whether this is a call to `var()`, which may be substituted in CSS for a
/// custom property value.
///
/// Functions that shadow plain CSS functions need to gracefully handle when
/// these arguments are passed in.
///
/// @nodoc
@internal
bool get isVar => false;
/// Returns Dart's `null` value if this is [sassNull], and returns [this]
/// otherwise.
Value? get realNull => this;
/// @nodoc
const Value();
/// Calls the appropriate visit method on [visitor].
///
/// @nodoc
@internal
T accept<T>(ValueVisitor<T> visitor);
/// Converts [sassIndex] into a Dart-style index into the list returned by
/// [asList].
///
/// Sass indexes are one-based, while Dart indexes are zero-based. Sass
/// indexes may also be negative in order to index from the end of the list.
///
/// Throws a [SassScriptException] if [sassIndex] isn't a number, if that
/// number isn't an integer, or if that integer isn't a valid index for
/// [asList]. If [sassIndex] came from a function argument, [name] is the
/// argument name (without the `$`). It's used for error reporting.
int sassIndexToListIndex(Value sassIndex, [String? name]) {
var index = sassIndex.assertNumber(name).assertInt(name);
if (index == 0) throw SassScriptException("List index may not be 0.", name);
if (index.abs() > lengthAsList) {
throw SassScriptException(
"Invalid index $sassIndex for a list with $lengthAsList elements.",
name);
}
return index < 0 ? lengthAsList + index : index - 1;
}
/// Throws a [SassScriptException] if [this] isn't a boolean.
///
/// Note that generally, functions should use [isTruthy] rather than requiring
/// a literal boolean.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SassBoolean assertBoolean([String? name]) =>
throw SassScriptException("$this is not a boolean.", name);
/// Throws a [SassScriptException] if [this] isn't a calculation.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SassCalculation assertCalculation([String? name]) =>
throw SassScriptException("$this is not a calculation.", name);
/// Throws a [SassScriptException] if [this] isn't a color.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SassColor assertColor([String? name]) =>
throw SassScriptException("$this is not a color.", name);
/// Throws a [SassScriptException] if [this] isn't a function reference.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SassFunction assertFunction([String? name]) =>
throw SassScriptException("$this is not a function reference.", name);
/// Throws a [SassScriptException] if [this] isn't a map.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SassMap assertMap([String? name]) =>
throw SassScriptException("$this is not a map.", name);
/// Returns [this] as a [SassMap] if it is one (including empty lists, which
/// count as empty maps) or returns `null` if it's not.
SassMap? tryMap() => null;
/// Throws a [SassScriptException] if [this] isn't a number.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SassNumber assertNumber([String? name]) =>
throw SassScriptException("$this is not a number.", name);
/// Throws a [SassScriptException] if [this] isn't a string.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SassString assertString([String? name]) =>
throw SassScriptException("$this is not a string.", name);
/// Converts a `selector-parse()`-style input into a string that can be
/// parsed.
///
/// Throws a [SassScriptException] if [this] isn't a type or a structure that
/// can be parsed as a selector.
String _selectorString([String? name]) {
var string = _selectorStringOrNull();
if (string != null) return string;
throw SassScriptException(
"$this is not a valid selector: it must be a string,\n"
"a list of strings, or a list of lists of strings.",
name);
}
/// Converts a `selector-parse()`-style input into a string that can be
/// parsed.
///
/// Returns `null` if [this] isn't a type or a structure that can be parsed as
/// a selector.
String? _selectorStringOrNull() {
if (this is SassString) return (this as SassString).text;
if (this is! SassList) return null;
var list = this as SassList;
if (list.asList.isEmpty) return null;
var result = <String>[];
switch (list.separator) {
case ListSeparator.comma:
for (var complex in list.asList) {
if (complex is SassString) {
result.add(complex.text);
} else if (complex is SassList &&
complex.separator == ListSeparator.space) {
var string = complex._selectorStringOrNull();
if (string == null) return null;
result.add(string);
} else {
return null;
}
}
break;
case ListSeparator.slash:
return null;
default:
for (var compound in list.asList) {
if (compound is SassString) {
result.add(compound.text);
} else {
return null;
}
}
break;
}
return result.join(list.separator == ListSeparator.comma ? ', ' : ' ');
}
/// Returns a new list containing [contents] that defaults to this value's
/// separator and brackets.
SassList withListContents(Iterable<Value> contents,
{ListSeparator? separator, bool? brackets}) {
return SassList(contents, separator ?? this.separator,
brackets: brackets ?? hasBrackets);
}
/// The SassScript `=` operation.
///
/// @nodoc
@internal
Value singleEquals(Value other) =>
SassString("${toCssString()}=${other.toCssString()}", quotes: false);
/// The SassScript `>` operation.
///
/// @nodoc
@internal
SassBoolean greaterThan(Value other) =>
throw SassScriptException('Undefined operation "$this > $other".');
/// The SassScript `>=` operation.
///
/// @nodoc
@internal
SassBoolean greaterThanOrEquals(Value other) =>
throw SassScriptException('Undefined operation "$this >= $other".');
/// The SassScript `<` operation.
///
/// @nodoc
@internal
SassBoolean lessThan(Value other) =>
throw SassScriptException('Undefined operation "$this < $other".');
/// The SassScript `<=` operation.
///
/// @nodoc
@internal
SassBoolean lessThanOrEquals(Value other) =>
throw SassScriptException('Undefined operation "$this <= $other".');
/// The SassScript `*` operation.
///
/// @nodoc
@internal
Value times(Value other) =>
throw SassScriptException('Undefined operation "$this * $other".');
/// The SassScript `%` operation.
///
/// @nodoc
@internal
Value modulo(Value other) =>
throw SassScriptException('Undefined operation "$this % $other".');
/// The SassScript `+` operation.
///
/// @nodoc
@internal
Value plus(Value other) {
if (other is SassString) {
return SassString(toCssString() + other.text, quotes: other.hasQuotes);
} else if (other is SassCalculation) {
throw SassScriptException('Undefined operation "$this + $other".');
} else {
return SassString(toCssString() + other.toCssString(), quotes: false);
}
}
/// The SassScript `-` operation.
///
/// @nodoc
@internal
Value minus(Value other) {
if (other is SassCalculation) {
throw SassScriptException('Undefined operation "$this - $other".');
} else {
return SassString("${toCssString()}-${other.toCssString()}",
quotes: false);
}
}
/// The SassScript `/` operation.
///
/// @nodoc
@internal
Value dividedBy(Value other) =>
SassString("${toCssString()}/${other.toCssString()}", quotes: false);
/// The SassScript unary `+` operation.
///
/// @nodoc
@internal
Value unaryPlus() => SassString("+${toCssString()}", quotes: false);
/// The SassScript unary `-` operation.
///
/// @nodoc
@internal
Value unaryMinus() => SassString("-${toCssString()}", quotes: false);
/// The SassScript unary `/` operation.
///
/// @nodoc
@internal
Value unaryDivide() => SassString("/${toCssString()}", quotes: false);
/// The SassScript unary `not` operation.
///
/// @nodoc
@internal
Value unaryNot() => sassFalse;
/// Returns a copy of [this] without [SassNumber.asSlash] set.
///
/// If this isn't a [SassNumber], returns it as-is.
///
/// @nodoc
@internal
Value withoutSlash() => this;
/// Returns a valid CSS representation of [this].
///
/// Throws a [SassScriptException] if [this] can't be represented in plain
/// CSS. Use [toString] instead to get a string representation even if this
/// isn't valid CSS.
//
// Internal-only: If [quote] is `false`, quoted strings are emitted without
// quotes.
String toCssString({@internal bool quote = true}) =>
serializeValue(this, quote: quote);
/// Returns a string representation of [this].
///
/// Note that this is equivalent to calling `inspect()` on the value, and thus
/// won't reflect the user's output settings. [toCssString] should be used
/// instead to convert [this] to CSS.
String toString() => serializeValue(this, inspect: true);
}
/// Extension methods that are only visible through the `sass_api` package.
///
/// These methods are considered less general-purpose and more liable to change
/// than the main [Value] interface.
///
/// {@category Value}
extension SassApiValue on Value {
/// Parses [this] as a selector list, in the same manner as the
/// `selector-parse()` function.
///
/// Throws a [SassScriptException] if this isn't a type that can be parsed as a
/// selector, or if parsing fails. If [allowParent] is `true`, this allows
/// [ParentSelector]s. Otherwise, they're considered parse errors.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SelectorList assertSelector({String? name, bool allowParent = false}) {
var string = _selectorString(name);
try {
return SelectorList.parse(string, allowParent: allowParent);
} on SassFormatException catch (error, stackTrace) {
// TODO(nweiz): colorize this if we're running in an environment where
// that works.
throwWithTrace(
SassScriptException(error.toString().replaceFirst("Error: ", ""), name),
stackTrace);
}
}
/// Parses [this] as a simple selector, in the same manner as the
/// `selector-parse()` function.
///
/// Throws a [SassScriptException] if this isn't a type that can be parsed as a
/// selector, or if parsing fails. If [allowParent] is `true`, this allows
/// [ParentSelector]s. Otherwise, they're considered parse errors.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
SimpleSelector assertSimpleSelector(
{String? name, bool allowParent = false}) {
var string = _selectorString(name);
try {
return SimpleSelector.parse(string, allowParent: allowParent);
} on SassFormatException catch (error, stackTrace) {
// TODO(nweiz): colorize this if we're running in an environment where
// that works.
throwWithTrace(
SassScriptException(error.toString().replaceFirst("Error: ", ""), name),
stackTrace);
}
}
/// Parses [this] as a compound selector, in the same manner as the
/// `selector-parse()` function.
///
/// Throws a [SassScriptException] if this isn't a type that can be parsed as a
/// selector, or if parsing fails. If [allowParent] is `true`, this allows
/// [ParentSelector]s. Otherwise, they're considered parse errors.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
CompoundSelector assertCompoundSelector(
{String? name, bool allowParent = false}) {
var string = _selectorString(name);
try {
return CompoundSelector.parse(string, allowParent: allowParent);
} on SassFormatException catch (error, stackTrace) {
// TODO(nweiz): colorize this if we're running in an environment where
// that works.
throwWithTrace(
SassScriptException(error.toString().replaceFirst("Error: ", ""), name),
stackTrace);
}
}
/// Parses [this] as a complex selector, in the same manner as the
/// `selector-parse()` function.
///
/// Throws a [SassScriptException] if this isn't a type that can be parsed as a
/// selector, or if parsing fails. If [allowParent] is `true`, this allows
/// [ParentSelector]s. Otherwise, they're considered parse errors.
///
/// If this came from a function argument, [name] is the argument name
/// (without the `$`). It's used for error reporting.
ComplexSelector assertComplexSelector(
{String? name, bool allowParent = false}) {
var string = _selectorString(name);
try {
return ComplexSelector.parse(string, allowParent: allowParent);
} on SassFormatException catch (error, stackTrace) {
// TODO(nweiz): colorize this if we're running in an environment where
// that works.
throwWithTrace(
SassScriptException(error.toString().replaceFirst("Error: ", ""), name),
stackTrace);
}
}
}