forked from sass/dart-sass
/
serialize.dart
1505 lines (1299 loc) · 46.8 KB
/
serialize.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
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 'dart:math' as math;
import 'dart:typed_data';
import 'package:charcode/charcode.dart';
import 'package:meta/meta.dart';
import 'package:source_maps/source_maps.dart';
import 'package:string_scanner/string_scanner.dart';
import '../ast/css.dart';
import '../ast/node.dart';
import '../ast/selector.dart';
import '../color_names.dart';
import '../exception.dart';
import '../parse/parser.dart';
import '../utils.dart';
import '../util/character.dart';
import '../util/no_source_map_buffer.dart';
import '../util/number.dart';
import '../util/source_map_buffer.dart';
import '../util/span.dart';
import '../value.dart';
import 'interface/css.dart';
import 'interface/selector.dart';
import 'interface/value.dart';
/// Converts [node] to a CSS string.
///
/// If [style] is passed, it controls the style of the resulting CSS. It
/// defaults to [OutputStyle.expanded].
///
/// If [inspect] is `true`, this will emit an unambiguous representation of the
/// source structure. Note however that, although this will be valid SCSS, it
/// may not be valid CSS. If [inspect] is `false` and [node] contains any values
/// that can't be represented in plain CSS, throws a [SassException].
///
/// If [sourceMap] is `true`, the returned [SerializeResult] will contain a
/// source map indicating how the original Sass files map to the compiled CSS.
///
/// If [charset] is `true`, this will include a `@charset` declaration or a BOM
/// if the stylesheet contains any non-ASCII characters.
SerializeResult serialize(CssNode node,
{OutputStyle? style,
bool inspect = false,
bool useSpaces = true,
int? indentWidth,
LineFeed? lineFeed,
bool sourceMap = false,
bool charset = true}) {
indentWidth ??= 2;
var visitor = _SerializeVisitor(
style: style,
inspect: inspect,
useSpaces: useSpaces,
indentWidth: indentWidth,
lineFeed: lineFeed,
sourceMap: sourceMap);
node.accept(visitor);
var css = visitor._buffer.toString();
String prefix;
if (charset && css.codeUnits.any((codeUnit) => codeUnit > 0x7F)) {
if (style == OutputStyle.compressed) {
prefix = '\uFEFF';
} else {
prefix = '@charset "UTF-8";\n';
}
} else {
prefix = '';
}
return SerializeResult(prefix + css,
sourceMap:
sourceMap ? visitor._buffer.buildSourceMap(prefix: prefix) : null);
}
/// Converts [value] to a CSS string.
///
/// If [inspect] is `true`, this will emit an unambiguous representation of the
/// source structure. Note however that, although this will be valid SCSS, it
/// may not be valid CSS. If [inspect] is `false` and [value] can't be
/// represented in plain CSS, throws a [SassScriptException].
///
/// If [quote] is `false`, quoted strings are emitted without quotes.
String serializeValue(Value value, {bool inspect = false, bool quote = true}) {
var visitor =
_SerializeVisitor(inspect: inspect, quote: quote, sourceMap: false);
value.accept(visitor);
return visitor._buffer.toString();
}
/// Converts [selector] to a CSS string.
///
/// If [inspect] is `true`, this will emit an unambiguous representation of the
/// source structure. Note however that, although this will be valid SCSS, it
/// may not be valid CSS. If [inspect] is `false` and [selector] can't be
/// represented in plain CSS, throws a [SassScriptException].
String serializeSelector(Selector selector, {bool inspect = false}) {
var visitor = _SerializeVisitor(inspect: inspect, sourceMap: false);
selector.accept(visitor);
return visitor._buffer.toString();
}
/// A visitor that converts CSS syntax trees to plain strings.
class _SerializeVisitor
implements CssVisitor<void>, ValueVisitor<void>, SelectorVisitor<void> {
/// A buffer that contains the CSS produced so far.
final SourceMapBuffer _buffer;
/// The current indentation of the CSS output.
var _indentation = 0;
/// The style of CSS to generate.
final OutputStyle _style;
/// Whether we're emitting an unambiguous representation of the source
/// structure, as opposed to valid CSS.
final bool _inspect;
/// Whether quoted strings should be emitted with quotes.
final bool _quote;
/// The character to use for indentation; either space or tab.
final int _indentCharacter;
/// The number of spaces or tabs to be used for indentation.
final int _indentWidth;
/// The characters to use for a line feed.
final LineFeed _lineFeed;
/// Whether we're emitting compressed output.
bool get _isCompressed => _style == OutputStyle.compressed;
_SerializeVisitor(
{OutputStyle? style,
bool inspect = false,
bool quote = true,
bool useSpaces = true,
int? indentWidth,
LineFeed? lineFeed,
bool sourceMap = true})
: _buffer = sourceMap ? SourceMapBuffer() : NoSourceMapBuffer(),
_style = style ?? OutputStyle.expanded,
_inspect = inspect,
_quote = quote,
_indentCharacter = useSpaces ? $space : $tab,
_indentWidth = indentWidth ?? 2,
_lineFeed = lineFeed ?? LineFeed.lf {
RangeError.checkValueInInterval(_indentWidth, 0, 10, "indentWidth");
}
void visitCssStylesheet(CssStylesheet node) {
CssNode? previous;
for (var child in node.children) {
if (_isInvisible(child)) continue;
if (previous != null) {
if (_requiresSemicolon(previous)) _buffer.writeCharCode($semicolon);
if (_isTrailingComment(child, previous)) {
_writeOptionalSpace();
} else {
_writeLineFeed();
if (previous.isGroupEnd) _writeLineFeed();
}
}
previous = child;
child.accept(this);
}
if (previous != null && _requiresSemicolon(previous) && !_isCompressed) {
_buffer.writeCharCode($semicolon);
}
}
void visitCssComment(CssComment node) {
_for(node, () {
// Preserve comments that start with `/*!`.
if (_isCompressed && !node.isPreserved) return;
var minimumIndentation = _minimumIndentation(node.text);
assert(minimumIndentation != -1);
if (minimumIndentation == null) {
_writeIndentation();
_buffer.write(node.text);
return;
}
minimumIndentation = math.min(minimumIndentation, node.span.start.column);
_writeIndentation();
_writeWithIndent(node.text, minimumIndentation);
});
}
void visitCssAtRule(CssAtRule node) {
_writeIndentation();
_for(node, () {
_buffer.writeCharCode($at);
_write(node.name);
var value = node.value;
if (value != null) {
_buffer.writeCharCode($space);
_write(value);
}
});
if (!node.isChildless) {
_writeOptionalSpace();
_visitChildren(node);
}
}
void visitCssMediaRule(CssMediaRule node) {
_writeIndentation();
_for(node, () {
_buffer.write("@media");
if (!_isCompressed || !node.queries.first.isCondition) {
_buffer.writeCharCode($space);
}
_writeBetween(node.queries, _commaSeparator, _visitMediaQuery);
});
_writeOptionalSpace();
_visitChildren(node);
}
void visitCssImport(CssImport node) {
_writeIndentation();
_for(node, () {
_buffer.write("@import");
_writeOptionalSpace();
_for(node.url, () => _writeImportUrl(node.url.value));
var modifiers = node.modifiers;
if (modifiers != null) {
_writeOptionalSpace();
_buffer.write(modifiers);
}
});
}
/// Writes [url], which is an import's URL, to the buffer.
void _writeImportUrl(String url) {
if (!_isCompressed || url.codeUnitAt(0) != $u) {
_buffer.write(url);
return;
}
// If this is url(...), remove the surrounding function. This is terser and
// it allows us to remove whitespace between `@import` and the URL.
var urlContents = url.substring(4, url.length - 1);
var maybeQuote = urlContents.codeUnitAt(0);
if (maybeQuote == $single_quote || maybeQuote == $double_quote) {
_buffer.write(urlContents);
} else {
// If the URL didn't contain quotes, write them manually.
_visitQuotedString(urlContents);
}
}
void visitCssKeyframeBlock(CssKeyframeBlock node) {
_writeIndentation();
_for(
node.selector,
() =>
_writeBetween(node.selector.value, _commaSeparator, _buffer.write));
_writeOptionalSpace();
_visitChildren(node);
}
void _visitMediaQuery(CssMediaQuery query) {
if (query.modifier != null) {
_buffer.write(query.modifier);
_buffer.writeCharCode($space);
}
if (query.type != null) {
_buffer.write(query.type);
if (query.features.isNotEmpty) {
_buffer.write(" and ");
}
}
_writeBetween(
query.features, _isCompressed ? "and " : " and ", _buffer.write);
}
void visitCssStyleRule(CssStyleRule node) {
_writeIndentation();
_for(node.selector, () => node.selector.value.accept(this));
_writeOptionalSpace();
_visitChildren(node);
}
void visitCssSupportsRule(CssSupportsRule node) {
_writeIndentation();
_for(node, () {
_buffer.write("@supports");
if (!(_isCompressed && node.condition.value.codeUnitAt(0) == $lparen)) {
_buffer.writeCharCode($space);
}
_write(node.condition);
});
_writeOptionalSpace();
_visitChildren(node);
}
void visitCssDeclaration(CssDeclaration node) {
_writeIndentation();
_write(node.name);
_buffer.writeCharCode($colon);
// If `node` is a custom property that was parsed as a normal Sass-syntax
// property (such as `#{--foo}: ...`), we serialize its value using the
// normal Sass property logic as well.
if (node.isCustomProperty && node.parsedAsCustomProperty) {
_for(node.value, () {
if (_isCompressed) {
_writeFoldedValue(node);
} else {
_writeReindentedValue(node);
}
});
} else {
_writeOptionalSpace();
try {
_buffer.forSpan(
node.valueSpanForMap, () => node.value.value.accept(this));
} on MultiSpanSassScriptException catch (error, stackTrace) {
throwWithTrace(
MultiSpanSassException(error.message, node.value.span,
error.primaryLabel, error.secondarySpans),
stackTrace);
} on SassScriptException catch (error, stackTrace) {
throwWithTrace(
SassException(error.message, node.value.span), stackTrace);
}
}
}
/// Emits the value of [node], with all newlines followed by whitespace
void _writeFoldedValue(CssDeclaration node) {
var scanner = StringScanner((node.value.value as SassString).text);
while (!scanner.isDone) {
var next = scanner.readChar();
if (next != $lf) {
_buffer.writeCharCode(next);
continue;
}
_buffer.writeCharCode($space);
while (isWhitespace(scanner.peekChar())) {
scanner.readChar();
}
}
}
/// Emits the value of [node], re-indented relative to the current indentation.
void _writeReindentedValue(CssDeclaration node) {
var value = (node.value.value as SassString).text;
var minimumIndentation = _minimumIndentation(value);
if (minimumIndentation == null) {
_buffer.write(value);
return;
} else if (minimumIndentation == -1) {
_buffer.write(trimAsciiRight(value, excludeEscape: true));
_buffer.writeCharCode($space);
return;
}
minimumIndentation =
math.min(minimumIndentation, node.name.span.start.column);
_writeWithIndent(value, minimumIndentation);
}
/// Returns the indentation level of the least-indented non-empty line in
/// [text] after the first.
///
/// Returns `null` if [text] contains no newlines, and -1 if it contains
/// newlines but no lines are indented.
int? _minimumIndentation(String text) {
var scanner = LineScanner(text);
while (!scanner.isDone && scanner.readChar() != $lf) {}
if (scanner.isDone) return scanner.peekChar(-1) == $lf ? -1 : null;
int? min;
while (!scanner.isDone) {
while (!scanner.isDone) {
var next = scanner.peekChar();
if (next != $space && next != $tab) break;
scanner.readChar();
}
if (scanner.isDone || scanner.scanChar($lf)) continue;
min = min == null ? scanner.column : math.min(min, scanner.column);
while (!scanner.isDone && scanner.readChar() != $lf) {}
}
return min ?? -1;
}
/// Writes [text] to [_buffer], replacing [minimumIndentation] with
/// [_indentation] for each non-empty line after the first.
///
/// Compresses trailing empty lines of [text] into a single trailing space.
void _writeWithIndent(String text, int minimumIndentation) {
var scanner = LineScanner(text);
// Write the first line as-is.
while (!scanner.isDone) {
var next = scanner.readChar();
if (next == $lf) break;
_buffer.writeCharCode(next);
}
while (true) {
assert(isWhitespace(scanner.peekChar(-1)));
// Scan forward until we hit non-whitespace or the end of [text].
var lineStart = scanner.position;
var newlines = 1;
while (true) {
// If we hit the end of [text], we still need to preserve the fact that
// whitespace exists because it could matter for custom properties.
if (scanner.isDone) {
_buffer.writeCharCode($space);
return;
}
var next = scanner.readChar();
if (next == $space || next == $tab) continue;
if (next != $lf) break;
lineStart = scanner.position;
newlines++;
}
_writeTimes($lf, newlines);
_writeIndentation();
_buffer.write(scanner.substring(lineStart + minimumIndentation));
// Scan and write until we hit a newline or the end of [text].
while (true) {
if (scanner.isDone) return;
var next = scanner.readChar();
if (next == $lf) break;
_buffer.writeCharCode(next);
}
}
}
// ## Values
void visitBoolean(SassBoolean value) => _buffer.write(value.value.toString());
void visitCalculation(SassCalculation value) {
_buffer.write(value.name);
_buffer.writeCharCode($lparen);
_writeBetween(value.arguments, _commaSeparator, _writeCalculationValue);
_buffer.writeCharCode($rparen);
}
void _writeCalculationValue(Object value) {
if (value is Value) {
value.accept(this);
} else if (value is CalculationInterpolation) {
_buffer.write(value.value);
} else if (value is CalculationOperation) {
var left = value.left;
var parenthesizeLeft = left is CalculationInterpolation ||
(left is CalculationOperation &&
left.operator.precedence < value.operator.precedence);
if (parenthesizeLeft) _buffer.writeCharCode($lparen);
_writeCalculationValue(left);
if (parenthesizeLeft) _buffer.writeCharCode($rparen);
var operatorWhitespace = !_isCompressed || value.operator.precedence == 1;
if (operatorWhitespace) _buffer.writeCharCode($space);
_buffer.write(value.operator.operator);
if (operatorWhitespace) _buffer.writeCharCode($space);
var right = value.right;
var parenthesizeRight = right is CalculationInterpolation ||
(right is CalculationOperation &&
_parenthesizeCalculationRhs(value.operator, right.operator));
if (parenthesizeRight) _buffer.writeCharCode($lparen);
_writeCalculationValue(right);
if (parenthesizeRight) _buffer.writeCharCode($rparen);
}
}
/// Returns whether the right-hand operation of a calculation should be
/// parenthesized.
///
/// In `a ? (b # c)`, `outer` is `?` and `right` is `#`.
bool _parenthesizeCalculationRhs(
CalculationOperator outer, CalculationOperator right) {
if (outer == CalculationOperator.dividedBy) return true;
if (outer == CalculationOperator.plus) return false;
return right == CalculationOperator.plus ||
right == CalculationOperator.minus;
}
void visitColor(SassColor value) {
// In compressed mode, emit colors in the shortest representation possible.
if (_isCompressed) {
if (!fuzzyEquals(value.alpha, 1)) {
_writeRgb(value);
} else {
var name = namesByColor[value];
var hexLength = _canUseShortHex(value) ? 4 : 7;
if (name != null && name.length <= hexLength) {
_buffer.write(name);
} else if (_canUseShortHex(value)) {
_buffer.writeCharCode($hash);
_buffer.writeCharCode(hexCharFor(value.red & 0xF));
_buffer.writeCharCode(hexCharFor(value.green & 0xF));
_buffer.writeCharCode(hexCharFor(value.blue & 0xF));
} else {
_buffer.writeCharCode($hash);
_writeHexComponent(value.red);
_writeHexComponent(value.green);
_writeHexComponent(value.blue);
}
}
} else {
var format = value.format;
if (format != null) {
if (format == ColorFormat.rgbFunction) {
_writeRgb(value);
} else if (format == ColorFormat.hslFunction) {
_writeHsl(value);
} else {
_buffer.write((format as SpanColorFormat).original);
}
} else if (namesByColor.containsKey(value) &&
// Always emit generated transparent colors in rgba format. This works
// around an IE bug. See sass/sass#1782.
!fuzzyEquals(value.alpha, 0)) {
_buffer.write(namesByColor[value]);
} else if (fuzzyEquals(value.alpha, 1)) {
_buffer.writeCharCode($hash);
_writeHexComponent(value.red);
_writeHexComponent(value.green);
_writeHexComponent(value.blue);
} else {
_writeRgb(value);
}
}
}
/// Writes [value] as an `rgb()` or `rgba()` function.
void _writeRgb(SassColor value) {
var opaque = fuzzyEquals(value.alpha, 1);
_buffer
..write(opaque ? "rgb(" : "rgba(")
..write(value.red)
..write(_commaSeparator)
..write(value.green)
..write(_commaSeparator)
..write(value.blue);
if (!opaque) {
_buffer.write(_commaSeparator);
_writeNumber(value.alpha);
}
_buffer.writeCharCode($rparen);
}
/// Writes [value] as an `hsl()` or `hsla()` function.
void _writeHsl(SassColor value) {
var opaque = fuzzyEquals(value.alpha, 1);
_buffer.write(opaque ? "hsl(" : "hsla(");
_writeNumber(value.hue);
_buffer.write("deg");
_buffer.write(_commaSeparator);
_writeNumber(value.saturation);
_buffer.writeCharCode($percent);
_buffer.write(_commaSeparator);
_writeNumber(value.lightness);
_buffer.writeCharCode($percent);
if (!opaque) {
_buffer.write(_commaSeparator);
_writeNumber(value.alpha);
}
_buffer.writeCharCode($rparen);
}
/// Returns whether [color]'s hex pair representation is symmetrical (e.g.
/// `FF`).
bool _isSymmetricalHex(int color) => color & 0xF == color >> 4;
/// Returns whether [color] can be represented as a short hexadecimal color
/// (e.g. `#fff`).
bool _canUseShortHex(SassColor color) =>
_isSymmetricalHex(color.red) &&
_isSymmetricalHex(color.green) &&
_isSymmetricalHex(color.blue);
/// Emits [color] as a hex character pair.
void _writeHexComponent(int color) {
assert(color < 0x100);
_buffer.writeCharCode(hexCharFor(color >> 4));
_buffer.writeCharCode(hexCharFor(color & 0xF));
}
void visitFunction(SassFunction function) {
if (!_inspect) {
throw SassScriptException("$function isn't a valid CSS value.");
}
_buffer.write("get-function(");
_visitQuotedString(function.callable.name);
_buffer.writeCharCode($rparen);
}
void visitList(SassList value) {
if (value.hasBrackets) {
_buffer.writeCharCode($lbracket);
} else if (value.asList.isEmpty) {
if (!_inspect) {
throw SassScriptException("() isn't a valid CSS value.");
}
_buffer.write("()");
return;
}
var singleton = _inspect &&
value.asList.length == 1 &&
(value.separator == ListSeparator.comma ||
value.separator == ListSeparator.slash);
if (singleton && !value.hasBrackets) _buffer.writeCharCode($lparen);
_writeBetween<Value>(
_inspect
? value.asList
: value.asList.where((element) => !element.isBlank),
_separatorString(value.separator),
_inspect
? (element) {
var needsParens = _elementNeedsParens(value.separator, element);
if (needsParens) _buffer.writeCharCode($lparen);
element.accept(this);
if (needsParens) _buffer.writeCharCode($rparen);
}
: (element) {
element.accept(this);
});
if (singleton) {
_buffer.write(value.separator.separator);
if (!value.hasBrackets) _buffer.writeCharCode($rparen);
}
if (value.hasBrackets) _buffer.writeCharCode($rbracket);
}
/// Returns the string to use to separate list items for lists with the given [separator].
String _separatorString(ListSeparator separator) {
switch (separator) {
case ListSeparator.comma:
return _commaSeparator;
case ListSeparator.slash:
return _isCompressed ? "/" : " / ";
case ListSeparator.space:
return " ";
default:
// This should never be used, but it may still be returned since
// [_separatorString] is invoked eagerly by [writeList] even for lists
// with only one elements.
return "";
}
}
/// Returns whether [value] needs parentheses as an element in a list with the
/// given [separator].
bool _elementNeedsParens(ListSeparator separator, Value value) {
if (value is SassList) {
if (value.asList.length < 2) return false;
if (value.hasBrackets) return false;
switch (separator) {
case ListSeparator.comma:
return value.separator == ListSeparator.comma;
case ListSeparator.slash:
return value.separator == ListSeparator.comma ||
value.separator == ListSeparator.slash;
default:
return value.separator != ListSeparator.undecided;
}
}
return false;
}
void visitMap(SassMap map) {
if (!_inspect) {
throw SassScriptException("$map isn't a valid CSS value.");
}
_buffer.writeCharCode($lparen);
_writeBetween<MapEntry<Value, Value>>(map.contents.entries, ", ", (entry) {
_writeMapElement(entry.key);
_buffer.write(": ");
_writeMapElement(entry.value);
});
_buffer.writeCharCode($rparen);
}
/// Writes [value] as key or value in a map, with parentheses as necessary.
void _writeMapElement(Value value) {
var needsParens = value is SassList &&
value.separator == ListSeparator.comma &&
!value.hasBrackets;
if (needsParens) _buffer.writeCharCode($lparen);
value.accept(this);
if (needsParens) _buffer.writeCharCode($rparen);
}
void visitNull() {
if (_inspect) _buffer.write("null");
}
void visitNumber(SassNumber value) {
var asSlash = value.asSlash;
if (asSlash != null) {
visitNumber(asSlash.item1);
_buffer.writeCharCode($slash);
visitNumber(asSlash.item2);
return;
}
_writeNumber(value.value);
if (!_inspect) {
if (value.numeratorUnits.length > 1 ||
value.denominatorUnits.isNotEmpty) {
throw SassScriptException("$value isn't a valid CSS value.");
}
if (value.numeratorUnits.isNotEmpty) {
_buffer.write(value.numeratorUnits.first);
}
} else {
_buffer.write(value.unitString);
}
}
/// Writes [number] without exponent notation and with at most
/// [SassNumber.precision] digits after the decimal point.
void _writeNumber(num number) {
// Dart always converts integers to strings in the obvious way, so all we
// have to do is clamp doubles that are close to being integers.
var integer = fuzzyAsInt(number);
if (integer != null) {
// Node.js still uses exponential notation for integers, so we have to
// handle it here.
_buffer.write(_removeExponent(integer.toString()));
return;
}
var text = _removeExponent(number.toString());
// Any double that's less than `SassNumber.precision + 2` digits long is
// guaranteed to be safe to emit directly, since it'll contain at most `0.`
// followed by [SassNumber.precision] digits.
var canWriteDirectly = text.length < SassNumber.precision + 2;
if (canWriteDirectly) {
if (_isCompressed && text.codeUnitAt(0) == $0) text = text.substring(1);
_buffer.write(text);
return;
}
_writeRounded(text);
}
/// If [text] is written in exponent notation, returns a string representation
/// of it without exponent notation.
///
/// Otherwise, returns [text] as-is.
String _removeExponent(String text) {
// Don't allocate this until we know [text] contains exponent notation.
StringBuffer? buffer;
var negative = text.codeUnitAt(0) == $minus;
late int exponent;
for (var i = 0; i < text.length; i++) {
var codeUnit = text.codeUnitAt(i);
if (codeUnit != $e) continue;
buffer = StringBuffer();
buffer.writeCharCode(text.codeUnitAt(0));
// If the number has more than one significant digit, the second
// character will be a decimal point that we don't want to include in
// the generated number.
if (negative) {
buffer.writeCharCode(text.codeUnitAt(1));
if (i > 3) buffer.write(text.substring(3, i));
} else {
if (i > 2) buffer.write(text.substring(2, i));
}
exponent = int.parse(text.substring(i + 1, text.length));
break;
}
if (buffer == null) return text;
if (exponent > 0) {
// Write an additional zero for each exponent digits other than those
// already written to the buffer. We subtract 1 from `buffer.length`
// because the first digit doesn't count towards the exponent. Subtract 1
// more for negative numbers because of the `-` written to the buffer.
var additionalZeroes =
exponent - (buffer.length - 1 - (negative ? 1 : 0));
for (var i = 0; i < additionalZeroes; i++) {
buffer.writeCharCode($0);
}
return buffer.toString();
} else {
var result = StringBuffer();
var negative = text.codeUnitAt(0) == $minus;
if (negative) result.writeCharCode($minus);
result.write("0.");
for (var i = -1; i > exponent; i--) {
result.writeCharCode($0);
}
result.write(negative ? buffer.toString().substring(1) : buffer);
return result.toString();
}
}
/// Assuming [text] is a number written without exponent notation, rounds it
/// to [SassNumber.precision] digits after the decimal and writes the result
/// to [_buffer].
void _writeRounded(String text) {
assert(RegExp(r"^-?\d+(\.\d+)?$").hasMatch(text),
'"$text" should be a number written without exponent notation.');
// Dart serializes all doubles with a trailing `.0`, even if they have
// integer values. In that case we definitely don't need to adjust for
// precision, so we can just write the number as-is without the `.0`.
if (text.endsWith(".0")) {
_buffer.write(text.substring(0, text.length - 2));
return;
}
// We need to ensure that we write at most [SassNumber.precision] digits
// after the decimal point, and that we round appropriately if necessary. To
// do this, we maintain an intermediate buffer of digits (both before and
// after the decimal point), which we then write to [_buffer] as text. We
// start writing after the first digit to give us room to round up to a
// higher decimal place than was represented in the original number.
var digits = Uint8List(text.length + 1);
var digitsIndex = 1;
// Write the digits before the decimal to [digits].
var textIndex = 0;
var negative = text.codeUnitAt(0) == $minus;
if (negative) textIndex++;
while (true) {
if (textIndex == text.length) {
// If we get here, [text] has no decmial point. It definitely doesn't
// need to be rounded; we can write it as-is.
_buffer.write(text);
return;
}
var codeUnit = text.codeUnitAt(textIndex++);
if (codeUnit == $dot) break;
digits[digitsIndex++] = asDecimal(codeUnit);
}
var firstFractionalDigit = digitsIndex;
// Only write at most [precision] digits after the decimal. If there aren't
// that many digits left in the number, write it as-is since no rounding or
// truncation is needed.
var indexAfterPrecision = textIndex + SassNumber.precision;
if (indexAfterPrecision >= text.length) {
_buffer.write(text);
return;
}
// Write the digits after the decimal to [digits].
while (textIndex < indexAfterPrecision) {
digits[digitsIndex++] = asDecimal(text.codeUnitAt(textIndex++));
}
// Round the trailing digits in [digits] up if necessary.
if (asDecimal(text.codeUnitAt(textIndex)) >= 5) {
while (true) {
// [digitsIndex] is guaranteed to be >0 here because we added a leading
// 0 to [digits] when we constructed it, so even if we round everything
// up [newDigit] will always be 1 when digitsIndex is 1.
var newDigit = ++digits[digitsIndex - 1];
if (newDigit != 10) break;
digitsIndex--;
}
}
// At most one of the following loops will actually execute. If we rounded
// digits up before the decimal point, the first loop will set those digits
// to 0 (rather than 10, which is not a valid decimal digit). On the other
// hand, if we have trailing zeros left after the decimal point, the second
// loop will move [digitsIndex] before them and cause them not to be
// written. Either way, [digitsIndex] will end up >= [firstFractionalDigit].
for (; digitsIndex < firstFractionalDigit; digitsIndex++) {
digits[digitsIndex] = 0;
}
while (digitsIndex > firstFractionalDigit && digits[digitsIndex - 1] == 0) {
digitsIndex--;
}
// Omit the minus sign if the number ended up being rounded to exactly zero,
// write "0" explicit to avoid adding a minus sign or omitting the number
// entirely in compressed mode.
if (digitsIndex == 2 && digits[0] == 0 && digits[1] == 0) {
_buffer.writeCharCode($0);
return;
}
if (negative) _buffer.writeCharCode($minus);
// Write the digits before the decimal point to [_buffer]. Omit the leading
// 0 that's added to [digits] to accommodate rounding, and in compressed
// mode omit the 0 before the decimal point as well.
var writtenIndex = 0;
if (digits[0] == 0) {
writtenIndex++;
if (_isCompressed && digits[1] == 0) writtenIndex++;
}
for (; writtenIndex < firstFractionalDigit; writtenIndex++) {
_buffer.writeCharCode(decimalCharFor(digits[writtenIndex]));
}
if (digitsIndex > firstFractionalDigit) {
_buffer.writeCharCode($dot);
for (; writtenIndex < digitsIndex; writtenIndex++) {
_buffer.writeCharCode(decimalCharFor(digits[writtenIndex]));
}
}
}
void visitString(SassString string) {
if (_quote && string.hasQuotes) {
_visitQuotedString(string.text);
} else {
_visitUnquotedString(string.text);
}
}
/// Writes a quoted string with [string] contents to [_buffer].
///
/// By default, this detects which type of quote to use based on the contents
/// of the string. If [forceDoubleQuote] is `true`, this always uses a double
/// quote.
void _visitQuotedString(String string, {bool forceDoubleQuote = false}) {
var includesSingleQuote = false;
var includesDoubleQuote = false;
var buffer = forceDoubleQuote ? _buffer : StringBuffer();
if (forceDoubleQuote) buffer.writeCharCode($double_quote);
for (var i = 0; i < string.length; i++) {
var char = string.codeUnitAt(i);
switch (char) {
case $single_quote:
if (forceDoubleQuote) {
buffer.writeCharCode($single_quote);
} else if (includesDoubleQuote) {
_visitQuotedString(string, forceDoubleQuote: true);
return;
} else {
includesSingleQuote = true;
buffer.writeCharCode($single_quote);
}
break;
case $double_quote:
if (forceDoubleQuote) {
buffer.writeCharCode($backslash);
buffer.writeCharCode($double_quote);
} else if (includesSingleQuote) {