/
stylesheet.dart
3801 lines (3325 loc) · 117 KB
/
stylesheet.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 'package:charcode/charcode.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p;
import 'package:source_span/source_span.dart';
import 'package:string_scanner/string_scanner.dart';
import 'package:tuple/tuple.dart';
import '../ast/sass.dart';
import '../color_names.dart';
import '../exception.dart';
import '../interpolation_buffer.dart';
import '../logger.dart';
import '../util/character.dart';
import '../utils.dart';
import '../util/nullable.dart';
import '../value.dart';
import 'parser.dart';
/// The base class for both the SCSS and indented syntax parsers.
///
/// Having a base class that's separate from both parsers allows us to make
/// explicit exactly which methods are different between the two. This allows
/// the author to know that if they're modifying the base class, the subclasses
/// generally won't need modification. Conversely, if they're modifying one
/// subclass, the other will likely need a parallel change.
///
/// All methods that are not intended to be accessed by external callers are
/// private, except where they have to be public for subclasses to refer to
/// them.
abstract class StylesheetParser extends Parser {
/// Whether we've consumed a rule other than `@charset`, `@forward`, or
/// `@use`.
var _isUseAllowed = true;
/// Whether the parser is currently parsing the contents of a mixin
/// declaration.
var _inMixin = false;
/// Whether the parser is currently parsing a content block passed to a mixin.
var _inContentBlock = false;
/// Whether the parser is currently parsing a control directive such as `@if`
/// or `@each`.
var _inControlDirective = false;
/// Whether the parser is currently parsing an unknown rule.
var _inUnknownAtRule = false;
/// Whether the parser is currently parsing a style rule.
var _inStyleRule = false;
/// Whether the parser is currently within a parenthesized expression.
var _inParentheses = false;
/// A map from all variable names that are assigned with `!global` in the
/// current stylesheet to the nodes where they're defined.
///
/// These are collected at parse time because they affect the variables
/// exposed by the module generated for this stylesheet, *even if they aren't
/// evaluated*. This allows us to ensure that the stylesheet always exposes
/// the same set of variable names no matter how it's evaluated.
final _globalVariables = <String, VariableDeclaration>{};
/// The silent comment this parser encountered previously.
@protected
SilentComment? lastSilentComment;
StylesheetParser(String contents, {Object? url, Logger? logger})
: super(contents, url: url, logger: logger);
// ## Statements
Stylesheet parse() {
return wrapSpanFormatException(() {
var start = scanner.state;
// Allow a byte-order mark at the beginning of the document.
scanner.scanChar(0xFEFF);
var statements = this.statements(() {
// Handle this specially so that [atRule] always returns a non-nullable
// Statement.
if (scanner.scan('@charset')) {
whitespace();
string();
return null;
}
return _statement(root: true);
});
scanner.expectDone();
/// Ensure that all global variable assignments produce a variable in this
/// stylesheet, even if they aren't evaluated. See sass/language#50.
statements.addAll(_globalVariables.values.map((declaration) =>
VariableDeclaration(declaration.name,
NullExpression(declaration.expression.span), declaration.span,
guarded: true)));
return Stylesheet.internal(statements, scanner.spanFrom(start),
plainCss: plainCss);
});
}
ArgumentDeclaration parseArgumentDeclaration() => _parseSingleProduction(() {
scanner.expectChar($at, name: "@-rule");
identifier();
whitespace();
identifier();
var arguments = _argumentDeclaration();
whitespace();
scanner.expectChar($lbrace);
return arguments;
});
Expression parseExpression() => _parseSingleProduction(expression);
VariableDeclaration parseVariableDeclaration() =>
_parseSingleProduction(() => lookingAtIdentifier()
? _variableDeclarationWithNamespace()
: variableDeclarationWithoutNamespace());
UseRule parseUseRule() => _parseSingleProduction(() {
var start = scanner.state;
scanner.expectChar($at, name: "@-rule");
expectIdentifier("use");
whitespace();
return _useRule(start);
});
/// Parses and returns [production] as the entire contents of [scanner].
T _parseSingleProduction<T>(T production()) {
return wrapSpanFormatException(() {
var result = production();
scanner.expectDone();
return result;
});
}
/// Parses a function signature of the format allowed by Node Sass's functions
/// option and returns its name and declaration.
///
/// Unlike normal function signatures, this allows parentheses to be omitted.
Tuple2<String, ArgumentDeclaration> parseSignature() {
return wrapSpanFormatException(() {
var name = identifier();
whitespace();
var arguments = scanner.peekChar() == $lparen
? _argumentDeclaration()
: ArgumentDeclaration.empty(scanner.emptySpan);
scanner.expectDone();
return Tuple2(name, arguments);
});
}
/// Consumes a statement that's allowed at the top level of the stylesheet or
/// within nested style and at rules.
///
/// If [root] is `true`, this parses at-rules that are allowed only at the
/// root of the stylesheet.
Statement _statement({bool root = false}) {
switch (scanner.peekChar()) {
case $at:
return atRule(() => _statement(), root: root);
case $plus:
if (!indented || !lookingAtIdentifier(1)) return _styleRule();
_isUseAllowed = false;
var start = scanner.state;
scanner.readChar();
return _includeRule(start);
case $equal:
if (!indented) return _styleRule();
_isUseAllowed = false;
var start = scanner.state;
scanner.readChar();
whitespace();
return _mixinRule(start);
case $rbrace:
scanner.error('unmatched "}".', length: 1);
default:
return _inStyleRule || _inUnknownAtRule || _inMixin || _inContentBlock
? _declarationOrStyleRule()
: _variableDeclarationOrStyleRule();
}
}
/// Consumes a namespaced variable declaration.
VariableDeclaration _variableDeclarationWithNamespace() {
var start = scanner.state;
var namespace = identifier();
scanner.expectChar($dot);
return variableDeclarationWithoutNamespace(namespace, start);
}
/// Consumes a variable declaration.
///
/// This never *consumes* a namespace, but if [namespace] is passed it will be
/// used for the declaration.
@protected
VariableDeclaration variableDeclarationWithoutNamespace(
[String? namespace, LineScannerState? start_]) {
var precedingComment = lastSilentComment;
lastSilentComment = null;
var start = start_ ?? scanner.state; // dart-lang/sdk#45348
var name = variableName();
if (namespace != null) _assertPublic(name, () => scanner.spanFrom(start));
if (plainCss) {
error("Sass variables aren't allowed in plain CSS.",
scanner.spanFrom(start));
}
whitespace();
scanner.expectChar($colon);
whitespace();
var value = expression();
var guarded = false;
var global = false;
var flagStart = scanner.state;
while (scanner.scanChar($exclamation)) {
var flag = identifier();
if (flag == 'default') {
guarded = true;
} else if (flag == 'global') {
if (namespace != null) {
error("!global isn't allowed for variables in other modules.",
scanner.spanFrom(flagStart));
}
global = true;
} else {
error("Invalid flag name.", scanner.spanFrom(flagStart));
}
whitespace();
flagStart = scanner.state;
}
expectStatementSeparator("variable declaration");
var declaration = VariableDeclaration(name, value, scanner.spanFrom(start),
namespace: namespace,
guarded: guarded,
global: global,
comment: precedingComment);
if (global) _globalVariables.putIfAbsent(name, () => declaration);
return declaration;
}
/// Consumes a namespaced [VariableDeclaration] or a [StyleRule].
Statement _variableDeclarationOrStyleRule() {
if (plainCss) return _styleRule();
// The indented syntax allows a single backslash to distinguish a style rule
// from old-style property syntax. We don't support old property syntax, but
// we do support the backslash because it's easy to do.
if (indented && scanner.scanChar($backslash)) return _styleRule();
if (!lookingAtIdentifier()) return _styleRule();
var start = scanner.state;
var variableOrInterpolation = _variableDeclarationOrInterpolation();
if (variableOrInterpolation is VariableDeclaration) {
return variableOrInterpolation;
} else {
return _styleRule(
InterpolationBuffer()
..addInterpolation(variableOrInterpolation as Interpolation),
start);
}
}
/// Consumes a [VariableDeclaration], a [Declaration], or a [StyleRule].
///
/// When parsing the children of a style rule, property declarations,
/// namespaced variable declarations, and nested style rules can all begin
/// with bare identifiers. In order to know which statement type to produce,
/// we need to disambiguate them. We use the following criteria:
///
/// * If the entity starts with an identifier followed by a period and a
/// dollar sign, it's a variable declaration. This is the simplest case,
/// because `.$` is used in and only in variable declarations.
///
/// * If the entity doesn't start with an identifier followed by a colon,
/// it's a selector. There are some additional mostly-unimportant cases
/// here to support various declaration hacks.
///
/// * If the colon is followed by another colon, it's a selector.
///
/// * Otherwise, if the colon is followed by anything other than
/// interpolation or a character that's valid as the beginning of an
/// identifier, it's a declaration.
///
/// * If the colon is followed by interpolation or a valid identifier, try
/// parsing it as a declaration value. If this fails, backtrack and parse
/// it as a selector.
///
/// * If the declaration value is valid but is followed by "{", backtrack and
/// parse it as a selector anyway. This ensures that ".foo:bar {" is always
/// parsed as a selector and never as a property with nested properties
/// beneath it.
Statement _declarationOrStyleRule() {
if (plainCss && _inStyleRule && !_inUnknownAtRule) {
return _propertyOrVariableDeclaration();
}
// The indented syntax allows a single backslash to distinguish a style rule
// from old-style property syntax. We don't support old property syntax, but
// we do support the backslash because it's easy to do.
if (indented && scanner.scanChar($backslash)) return _styleRule();
var start = scanner.state;
var declarationOrBuffer = _declarationOrBuffer();
return declarationOrBuffer is Statement
? declarationOrBuffer
: _styleRule(declarationOrBuffer as InterpolationBuffer, start);
}
/// Tries to parse a variable or property declaration, and returns the value
/// parsed so far if it fails.
///
/// This can return either an [InterpolationBuffer], indicating that it
/// couldn't consume a declaration and that selector parsing should be
/// attempted; or it can return a [Declaration] or a [VariableDeclaration],
/// indicating that it successfully consumed a declaration.
dynamic _declarationOrBuffer() {
var start = scanner.state;
var nameBuffer = InterpolationBuffer();
// Allow the "*prop: val", ":prop: val", "#prop: val", and ".prop: val"
// hacks.
var first = scanner.peekChar();
var startsWithPunctuation = false;
if (first == $colon ||
first == $asterisk ||
first == $dot ||
(first == $hash && scanner.peekChar(1) != $lbrace)) {
startsWithPunctuation = true;
nameBuffer.writeCharCode(scanner.readChar());
nameBuffer.write(rawText(whitespace));
}
if (!_lookingAtInterpolatedIdentifier()) return nameBuffer;
var variableOrInterpolation = startsWithPunctuation
? interpolatedIdentifier()
: _variableDeclarationOrInterpolation();
if (variableOrInterpolation is VariableDeclaration) {
return variableOrInterpolation;
} else {
nameBuffer.addInterpolation(variableOrInterpolation as Interpolation);
}
_isUseAllowed = false;
if (scanner.matches("/*")) nameBuffer.write(rawText(loudComment));
var midBuffer = StringBuffer();
midBuffer.write(rawText(whitespace));
var beforeColon = scanner.state;
if (!scanner.scanChar($colon)) {
if (midBuffer.isNotEmpty) nameBuffer.writeCharCode($space);
return nameBuffer;
}
midBuffer.writeCharCode($colon);
// Parse custom properties as declarations no matter what.
var name = nameBuffer.interpolation(scanner.spanFrom(start, beforeColon));
if (name.initialPlain.startsWith('--')) {
var value = StringExpression(_interpolatedDeclarationValue());
expectStatementSeparator("custom property");
return Declaration(name, value, scanner.spanFrom(start));
}
if (scanner.scanChar($colon)) {
return nameBuffer
..write(midBuffer)
..writeCharCode($colon);
} else if (indented && _lookingAtInterpolatedIdentifier()) {
// In the indented syntax, `foo:bar` is always considered a selector
// rather than a property.
return nameBuffer..write(midBuffer);
}
var postColonWhitespace = rawText(whitespace);
if (lookingAtChildren()) {
return _withChildren(_declarationChild, start,
(children, span) => Declaration.nested(name, children, span));
}
midBuffer.write(postColonWhitespace);
var couldBeSelector =
postColonWhitespace.isEmpty && _lookingAtInterpolatedIdentifier();
var beforeDeclaration = scanner.state;
Expression value;
try {
value = lookingAtChildren()
? StringExpression(Interpolation([], scanner.emptySpan), quotes: true)
: expression();
if (lookingAtChildren()) {
// Properties that are ambiguous with selectors can't have additional
// properties nested beneath them, so we force an error. This will be
// caught below and cause the text to be reparsed as a selector.
if (couldBeSelector) expectStatementSeparator();
} else if (!atEndOfStatement()) {
// Force an exception if there isn't a valid end-of-property character
// but don't consume that character. This will also cause the text to be
// reparsed.
expectStatementSeparator();
}
} on FormatException catch (_) {
if (!couldBeSelector) rethrow;
// If the value would be followed by a semicolon, it's definitely supposed
// to be a property, not a selector.
scanner.state = beforeDeclaration;
var additional = almostAnyValue();
if (!indented && scanner.peekChar() == $semicolon) rethrow;
nameBuffer.write(midBuffer);
nameBuffer.addInterpolation(additional);
return nameBuffer;
}
if (lookingAtChildren()) {
return _withChildren(
_declarationChild,
start,
(children, span) =>
Declaration.nested(name, children, span, value: value));
} else {
expectStatementSeparator();
return Declaration(name, value, scanner.spanFrom(start));
}
}
/// Tries to parse a namespaced [VariableDeclaration], and returns the value
/// parsed so far if it fails.
///
/// This can return either an [Interpolation], indicating that it couldn't
/// consume a variable declaration and that property declaration or selector
/// parsing should be attempted; or it can return a [VariableDeclaration],
/// indicating that it successfully consumed a variable declaration.
dynamic _variableDeclarationOrInterpolation() {
if (!lookingAtIdentifier()) return interpolatedIdentifier();
var start = scanner.state;
var identifier = this.identifier();
if (scanner.matches(".\$")) {
scanner.readChar();
return variableDeclarationWithoutNamespace(identifier, start);
} else {
var buffer = InterpolationBuffer()..write(identifier);
// Parse the rest of an interpolated identifier if one exists, so callers
// don't have to.
if (_lookingAtInterpolatedIdentifierBody()) {
buffer.addInterpolation(interpolatedIdentifier());
}
return buffer.interpolation(scanner.spanFrom(start));
}
}
/// Consumes a [StyleRule], optionally with a [buffer] that may contain some
/// text that has already been parsed.
StyleRule _styleRule(
[InterpolationBuffer? buffer, LineScannerState? start_]) {
_isUseAllowed = false;
var start = start_ ?? scanner.state; // dart-lang/sdk#45348
var interpolation = styleRuleSelector();
if (buffer != null) {
buffer.addInterpolation(interpolation);
interpolation = buffer.interpolation(scanner.spanFrom(start));
}
if (interpolation.contents.isEmpty) scanner.error('expected "}".');
var wasInStyleRule = _inStyleRule;
_inStyleRule = true;
return _withChildren(_statement, start, (children, span) {
if (indented && children.isEmpty) {
warn("This selector doesn't have any properties and won't be rendered.",
interpolation.span);
}
_inStyleRule = wasInStyleRule;
return StyleRule(interpolation, children, scanner.spanFrom(start));
});
}
/// Consumes either a property declaration or a namespaced variable
/// declaration.
///
/// This is only used in contexts where declarations are allowed but style
/// rules are not, such as nested declarations. Otherwise,
/// [_declarationOrStyleRule] is used instead.
///
/// If [parseCustomProperties] is `true`, properties that begin with `--` will
/// be parsed using custom property parsing rules.
Statement _propertyOrVariableDeclaration(
{bool parseCustomProperties = true}) {
var start = scanner.state;
Interpolation name;
// Allow the "*prop: val", ":prop: val", "#prop: val", and ".prop: val"
// hacks.
var first = scanner.peekChar();
if (first == $colon ||
first == $asterisk ||
first == $dot ||
(first == $hash && scanner.peekChar(1) != $lbrace)) {
var nameBuffer = InterpolationBuffer();
nameBuffer.writeCharCode(scanner.readChar());
nameBuffer.write(rawText(whitespace));
nameBuffer.addInterpolation(interpolatedIdentifier());
name = nameBuffer.interpolation(scanner.spanFrom(start));
} else if (!plainCss) {
var variableOrInterpolation = _variableDeclarationOrInterpolation();
if (variableOrInterpolation is VariableDeclaration) {
return variableOrInterpolation;
} else {
name = variableOrInterpolation as Interpolation;
}
} else {
name = interpolatedIdentifier();
}
whitespace();
scanner.expectChar($colon);
if (parseCustomProperties && name.initialPlain.startsWith('--')) {
var value = StringExpression(_interpolatedDeclarationValue());
expectStatementSeparator("custom property");
return Declaration(name, value, scanner.spanFrom(start));
}
whitespace();
if (lookingAtChildren()) {
if (plainCss) {
scanner.error("Nested declarations aren't allowed in plain CSS.");
}
return _withChildren(_declarationChild, start,
(children, span) => Declaration.nested(name, children, span));
}
var value = expression();
if (lookingAtChildren()) {
if (plainCss) {
scanner.error("Nested declarations aren't allowed in plain CSS.");
}
return _withChildren(
_declarationChild,
start,
(children, span) =>
Declaration.nested(name, children, span, value: value));
} else {
expectStatementSeparator();
return Declaration(name, value, scanner.spanFrom(start));
}
}
/// Consumes a statement that's allowed within a declaration.
Statement _declarationChild() {
if (scanner.peekChar() == $at) return _declarationAtRule();
return _propertyOrVariableDeclaration(parseCustomProperties: false);
}
// ## At Rules
/// Consumes an at-rule.
///
/// This consumes at-rules that are allowed at all levels of the document; the
/// [child] parameter is called to consume any at-rules that are specifically
/// allowed in the caller's context.
///
/// If [root] is `true`, this parses at-rules that are allowed only at the
/// root of the stylesheet.
@protected
Statement atRule(Statement child(), {bool root = false}) {
// NOTE: this logic is largely duplicated in CssParser.atRule. Most changes
// here should be mirrored there.
var start = scanner.state;
scanner.expectChar($at, name: "@-rule");
var name = interpolatedIdentifier();
whitespace();
// We want to set [_isUseAllowed] to `false` *unless* we're parsing
// `@charset`, `@forward`, or `@use`. To avoid double-comparing the rule
// name, we always set it to `false` and then set it back to its previous
// value if we're parsing an allowed rule.
var wasUseAllowed = _isUseAllowed;
_isUseAllowed = false;
switch (name.asPlain) {
case "at-root":
return _atRootRule(start);
case "content":
return _contentRule(start);
case "debug":
return _debugRule(start);
case "each":
return _eachRule(start, child);
case "else":
return _disallowedAtRule(start);
case "error":
return _errorRule(start);
case "extend":
return _extendRule(start);
case "for":
return _forRule(start, child);
case "forward":
_isUseAllowed = wasUseAllowed;
if (!root) _disallowedAtRule(start);
return _forwardRule(start);
case "function":
return _functionRule(start);
case "if":
return _ifRule(start, child);
case "import":
return _importRule(start);
case "include":
return _includeRule(start);
case "media":
return mediaRule(start);
case "mixin":
return _mixinRule(start);
case "-moz-document":
return mozDocumentRule(start, name);
case "return":
return _disallowedAtRule(start);
case "supports":
return supportsRule(start);
case "use":
_isUseAllowed = wasUseAllowed;
if (!root) _disallowedAtRule(start);
return _useRule(start);
case "warn":
return _warnRule(start);
case "while":
return _whileRule(start, child);
default:
return unknownAtRule(start, name);
}
}
/// Consumes an at-rule allowed within a property declaration.
Statement _declarationAtRule() {
var start = scanner.state;
var name = _plainAtRuleName();
switch (name) {
case "content":
return _contentRule(start);
case "debug":
return _debugRule(start);
case "each":
return _eachRule(start, _declarationChild);
case "else":
return _disallowedAtRule(start);
case "error":
return _errorRule(start);
case "for":
return _forRule(start, _declarationChild);
case "if":
return _ifRule(start, _declarationChild);
case "include":
return _includeRule(start);
case "warn":
return _warnRule(start);
case "while":
return _whileRule(start, _declarationChild);
default:
return _disallowedAtRule(start);
}
}
/// Consumes a statement allowed within a function.
Statement _functionChild() {
if (scanner.peekChar() != $at) {
var state = scanner.state;
try {
return _variableDeclarationWithNamespace();
} on SourceSpanFormatException catch (variableDeclarationError) {
scanner.state = state;
// If a variable declaration failed to parse, it's possible the user
// thought they could write a style rule or property declaration in a
// function. If so, throw a more helpful error message.
Statement statement;
try {
statement = _declarationOrStyleRule();
} on SourceSpanFormatException catch (_) {
throw variableDeclarationError;
}
error(
"@function rules may not contain "
"${statement is StyleRule ? "style rules" : "declarations"}.",
statement.span);
}
}
var start = scanner.state;
switch (_plainAtRuleName()) {
case "debug":
return _debugRule(start);
case "each":
return _eachRule(start, _functionChild);
case "else":
return _disallowedAtRule(start);
case "error":
return _errorRule(start);
case "for":
return _forRule(start, _functionChild);
case "if":
return _ifRule(start, _functionChild);
case "return":
return _returnRule(start);
case "warn":
return _warnRule(start);
case "while":
return _whileRule(start, _functionChild);
default:
return _disallowedAtRule(start);
}
}
/// Consumes an at-rule's name, with interpolation disallowed.
String _plainAtRuleName() {
scanner.expectChar($at, name: "@-rule");
var name = identifier();
whitespace();
return name;
}
/// Consumes an `@at-root` rule.
///
/// [start] should point before the `@`.
AtRootRule _atRootRule(LineScannerState start) {
if (scanner.peekChar() == $lparen) {
var query = _atRootQuery();
whitespace();
return _withChildren(_statement, start,
(children, span) => AtRootRule(children, span, query: query));
} else if (lookingAtChildren()) {
return _withChildren(
_statement, start, (children, span) => AtRootRule(children, span));
} else {
var child = _styleRule();
return AtRootRule([child], scanner.spanFrom(start));
}
}
/// Consumes a query expression of the form `(foo: bar)`.
Interpolation _atRootQuery() {
if (scanner.peekChar() == $hash) {
var interpolation = singleInterpolation();
return Interpolation([interpolation], interpolation.span);
}
var start = scanner.state;
var buffer = InterpolationBuffer();
scanner.expectChar($lparen);
buffer.writeCharCode($lparen);
whitespace();
buffer.add(expression());
if (scanner.scanChar($colon)) {
whitespace();
buffer.writeCharCode($colon);
buffer.writeCharCode($space);
buffer.add(expression());
}
scanner.expectChar($rparen);
whitespace();
buffer.writeCharCode($rparen);
return buffer.interpolation(scanner.spanFrom(start));
}
/// Consumes a `@content` rule.
///
/// [start] should point before the `@`.
ContentRule _contentRule(LineScannerState start) {
if (!_inMixin) {
error("@content is only allowed within mixin declarations.",
scanner.spanFrom(start));
}
whitespace();
var arguments = scanner.peekChar() == $lparen
? _argumentInvocation(mixin: true)
: ArgumentInvocation.empty(scanner.emptySpan);
expectStatementSeparator("@content rule");
return ContentRule(arguments, scanner.spanFrom(start));
}
/// Consumes a `@debug` rule.
///
/// [start] should point before the `@`.
DebugRule _debugRule(LineScannerState start) {
var value = expression();
expectStatementSeparator("@debug rule");
return DebugRule(value, scanner.spanFrom(start));
}
/// Consumes an `@each` rule.
///
/// [start] should point before the `@`. [child] is called to consume any
/// children that are specifically allowed in the caller's context.
EachRule _eachRule(LineScannerState start, Statement child()) {
var wasInControlDirective = _inControlDirective;
_inControlDirective = true;
var variables = [variableName()];
whitespace();
while (scanner.scanChar($comma)) {
whitespace();
variables.add(variableName());
whitespace();
}
expectIdentifier("in");
whitespace();
var list = expression();
return _withChildren(child, start, (children, span) {
_inControlDirective = wasInControlDirective;
return EachRule(variables, list, children, span);
});
}
/// Consumes an `@error` rule.
///
/// [start] should point before the `@`.
ErrorRule _errorRule(LineScannerState start) {
var value = expression();
expectStatementSeparator("@error rule");
return ErrorRule(value, scanner.spanFrom(start));
}
/// Consumes an `@extend` rule.
///
/// [start] should point before the `@`.
ExtendRule _extendRule(LineScannerState start) {
if (!_inStyleRule && !_inMixin && !_inContentBlock) {
error("@extend may only be used within style rules.",
scanner.spanFrom(start));
}
var value = almostAnyValue();
var optional = scanner.scanChar($exclamation);
if (optional) expectIdentifier("optional");
expectStatementSeparator("@extend rule");
return ExtendRule(value, scanner.spanFrom(start), optional: optional);
}
/// Consumes a function declaration.
///
/// [start] should point before the `@`.
FunctionRule _functionRule(LineScannerState start) {
var precedingComment = lastSilentComment;
lastSilentComment = null;
var name = identifier(normalize: true);
whitespace();
var arguments = _argumentDeclaration();
if (_inMixin || _inContentBlock) {
error("Mixins may not contain function declarations.",
scanner.spanFrom(start));
} else if (_inControlDirective) {
error("Functions may not be declared in control directives.",
scanner.spanFrom(start));
}
switch (unvendor(name)) {
case "calc":
case "element":
case "expression":
case "url":
case "and":
case "or":
case "not":
case "clamp":
error("Invalid function name.", scanner.spanFrom(start));
}
whitespace();
return _withChildren(
_functionChild,
start,
(children, span) => FunctionRule(name, arguments, children, span,
comment: precedingComment));
}
/// Consumes a `@for` rule.
///
/// [start] should point before the `@`. [child] is called to consume any
/// children that are specifically allowed in the caller's context.
ForRule _forRule(LineScannerState start, Statement child()) {
var wasInControlDirective = _inControlDirective;
_inControlDirective = true;
var variable = variableName();
whitespace();
expectIdentifier("from");
whitespace();
bool? exclusive;
var from = expression(until: () {
if (!lookingAtIdentifier()) return false;
if (scanIdentifier("to")) {
exclusive = true;
return true;
} else if (scanIdentifier("through")) {
exclusive = false;
return true;
} else {
return false;
}
});
if (exclusive == null) scanner.error('Expected "to" or "through".');
whitespace();
var to = expression();
return _withChildren(child, start, (children, span) {
_inControlDirective = wasInControlDirective;
return ForRule(variable, from, to, children, span,
exclusive: exclusive!); // dart-lang/sdk#45348
});
}
/// Consumes a `@forward` rule.
///
/// [start] should point before the `@`.
ForwardRule _forwardRule(LineScannerState start) {
var url = _urlString();
whitespace();
String? prefix;
if (scanIdentifier("as")) {
whitespace();
prefix = identifier(normalize: true);
scanner.expectChar($asterisk);
whitespace();
}
Set<String>? shownMixinsAndFunctions;
Set<String>? shownVariables;
Set<String>? hiddenMixinsAndFunctions;
Set<String>? hiddenVariables;
if (scanIdentifier("show")) {
var members = _memberList();
shownMixinsAndFunctions = members.item1;
shownVariables = members.item2;
} else if (scanIdentifier("hide")) {
var members = _memberList();
hiddenMixinsAndFunctions = members.item1;
hiddenVariables = members.item2;
}
var configuration = _configuration(allowGuarded: true);
expectStatementSeparator("@forward rule");
var span = scanner.spanFrom(start);
if (!_isUseAllowed) {
error("@forward rules must be written before any other rules.", span);
}
if (shownMixinsAndFunctions != null) {
return ForwardRule.show(
url, shownMixinsAndFunctions, shownVariables!, span,
prefix: prefix, configuration: configuration);
} else if (hiddenMixinsAndFunctions != null) {
return ForwardRule.hide(
url, hiddenMixinsAndFunctions, hiddenVariables!, span,
prefix: prefix, configuration: configuration);
} else {
return ForwardRule(url, span,
prefix: prefix, configuration: configuration);