-
Notifications
You must be signed in to change notification settings - Fork 75
/
StylesheetParser.php
4543 lines (3726 loc) · 149 KB
/
StylesheetParser.php
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
<?php
/**
* SCSSPHP
*
* @copyright 2012-2020 Leaf Corcoran
*
* @license http://opensource.org/licenses/MIT MIT
*
* @link http://scssphp.github.io/scssphp
*/
namespace ScssPhp\ScssPhp\Parser;
use League\Uri\Exceptions\SyntaxError;
use League\Uri\Uri;
use ScssPhp\ScssPhp\Ast\Sass\Argument;
use ScssPhp\ScssPhp\Ast\Sass\ArgumentDeclaration;
use ScssPhp\ScssPhp\Ast\Sass\ArgumentInvocation;
use ScssPhp\ScssPhp\Ast\Sass\Expression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\BinaryOperationExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\BinaryOperator;
use ScssPhp\ScssPhp\Ast\Sass\Expression\BooleanExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\CalculationExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\ColorExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\FunctionExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\IfExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\InterpolatedFunctionExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\ListExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\MapExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\NullExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\NumberExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\ParenthesizedExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\SelectorExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\StringExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\SupportsExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\UnaryOperationExpression;
use ScssPhp\ScssPhp\Ast\Sass\Expression\UnaryOperator;
use ScssPhp\ScssPhp\Ast\Sass\Expression\VariableExpression;
use ScssPhp\ScssPhp\Ast\Sass\Import;
use ScssPhp\ScssPhp\Ast\Sass\Import\DynamicImport;
use ScssPhp\ScssPhp\Ast\Sass\Import\StaticImport;
use ScssPhp\ScssPhp\Ast\Sass\Interpolation;
use ScssPhp\ScssPhp\Ast\Sass\Statement;
use ScssPhp\ScssPhp\Ast\Sass\Statement\AtRootRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\AtRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\ContentBlock;
use ScssPhp\ScssPhp\Ast\Sass\Statement\ContentRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\DebugRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\Declaration;
use ScssPhp\ScssPhp\Ast\Sass\Statement\EachRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\ElseClause;
use ScssPhp\ScssPhp\Ast\Sass\Statement\ErrorRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\ExtendRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\ForRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\FunctionRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\IfClause;
use ScssPhp\ScssPhp\Ast\Sass\Statement\IfRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\ImportRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\IncludeRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\MediaRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\MixinRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\ReturnRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\SilentComment;
use ScssPhp\ScssPhp\Ast\Sass\Statement\StyleRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\Stylesheet;
use ScssPhp\ScssPhp\Ast\Sass\Statement\SupportsRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\VariableDeclaration;
use ScssPhp\ScssPhp\Ast\Sass\Statement\WarnRule;
use ScssPhp\ScssPhp\Ast\Sass\Statement\WhileRule;
use ScssPhp\ScssPhp\Ast\Sass\SupportsCondition;
use ScssPhp\ScssPhp\Ast\Sass\SupportsCondition\SupportsAnything;
use ScssPhp\ScssPhp\Ast\Sass\SupportsCondition\SupportsDeclaration;
use ScssPhp\ScssPhp\Ast\Sass\SupportsCondition\SupportsFunction;
use ScssPhp\ScssPhp\Ast\Sass\SupportsCondition\SupportsInterpolation;
use ScssPhp\ScssPhp\Ast\Sass\SupportsCondition\SupportsNegation;
use ScssPhp\ScssPhp\Ast\Sass\SupportsCondition\SupportsOperation;
use ScssPhp\ScssPhp\Colors;
use ScssPhp\ScssPhp\Exception\SassFormatException;
use ScssPhp\ScssPhp\Logger\LoggerInterface;
use ScssPhp\ScssPhp\SourceSpan\FileSpan;
use ScssPhp\ScssPhp\Util;
use ScssPhp\ScssPhp\Util\Character;
use ScssPhp\ScssPhp\Util\Path;
use ScssPhp\ScssPhp\Util\StringUtil;
use ScssPhp\ScssPhp\Value\ListSeparator;
use ScssPhp\ScssPhp\Value\SassColor;
use ScssPhp\ScssPhp\Value\SpanColorFormat;
/**
* @internal
*/
abstract class StylesheetParser extends Parser
{
/**
* The silent comment this parser encountered previously.
*
* @var SilentComment|null
*/
protected $lastSilentComment;
/**
* Whether we've consumed a rule other than `@charset`, `@forward`, or `@use`.
*
* @var bool
*/
private $isUseAllowed = true;
/**
* Whether the parser is currently parsing the contents of a mixin declaration.
*
* @var bool
*/
private $inMixin = false;
/**
* Whether the parser is currently parsing a content block passed to a mixin.
*
* @var bool
*/
private $inContentBlock = false;
/**
* Whether the parser is currently parsing a control directive such as `@if`
* or `@each`.
*
* @var bool
*/
private $inControlDirective = false;
/**
* Whether the parser is currently parsing an unknown rule.
*
* @var bool
*/
private $inUnknownAtRule = false;
/**
* Whether the parser is currently parsing a style rule.
*
* @var bool
*/
private $inStyleRule = false;
/**
* Whether the parser is currently within a parenthesized expression.
*
* @var bool
*/
private $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.
*
* @var array<string, VariableDeclaration>
*/
private $globalVariables = [];
/**
* @var \Closure
* @readonly
*/
private $statementCallable;
/**
* @var \Closure
* @readonly
*/
private $declarationChildCallable;
/**
* @var \Closure
* @readonly
*/
private $functionChildCallable;
public function __construct(string $contents, ?LoggerInterface $logger = null, ?string $sourceUrl = null)
{
parent::__construct($contents, $logger, $sourceUrl);
// Store callables for some private methods, to ensure they pass callable typehints when passed
// to parent methods expecting a callable, due to the semantic of PHP array callables.
$this->statementCallable = \Closure::fromCallable([$this, 'statement']);
$this->declarationChildCallable = \Closure::fromCallable([$this, 'declarationChild']);
$this->functionChildCallable = \Closure::fromCallable([$this, 'functionChild']);
}
/**
* @throws SassFormatException when parsing fails
*/
public function parse(): Stylesheet
{
try {
$start = $this->scanner->getPosition();
// Allow a byte-order mark at the beginning of the document.
$this->scanner->scan("\u{FEFF}");
$statements = $this->statements(function () {
// Handle this specially so that {@see atRule} always returns a non-nullable Statement.
if ($this->scanner->scan('@charset')) {
$this->whitespace();
$this->string();
return null;
}
return $this->statement(true);
});
$this->scanner->expectDone();
// Ensure that all global variable assignments produce a variable in this
// stylesheet, even if they aren't evaluated. See sass/language#50.
foreach ($this->globalVariables as $declaration) {
$statements[] = new VariableDeclaration($declaration->getName(), new NullExpression($declaration->getExpression()->getSpan()), $declaration->getSpan(), null, true);
}
return new Stylesheet($statements, $this->scanner->spanFrom($start), $this->isPlainCss());
} catch (FormatException $e) {
throw $this->wrapException($e);
}
}
public function parseArgumentDeclaration(): ArgumentDeclaration
{
try {
$this->scanner->expectChar('@', '@-rule');
$this->identifier();
$this->whitespace();
$this->identifier();
$arguments = $this->argumentDeclaration();
$this->whitespace();
$this->scanner->expectChar('{');
$this->scanner->expectDone();
return $arguments;
} catch (FormatException $e) {
throw $this->wrapException($e);
}
}
/**
* 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.
*/
private function statement(bool $root = false): Statement
{
switch ($this->scanner->peekChar()) {
case '@':
return $this->atRule($this->statementCallable, $root);
case '+':
if (!$this->isIndented()) {
return $this->styleRule();
}
throw new \BadMethodCallException('The parsing of the indented syntax is not implemented.');
case '=':
if (!$this->isIndented()) {
return $this->styleRule();
}
throw new \BadMethodCallException('The parsing of the indented syntax is not implemented.');
case '}':
$this->scanner->error('unmatched "}".');
default:
if ($this->inStyleRule || $this->inUnknownAtRule || $this->inMixin || $this->inContentBlock) {
return $this->declarationOrStyleRule();
}
return $this->variableDeclarationOrStyleRule();
}
}
/**
* Consumes a namespaced variable declaration.
*
* @throws FormatException
*/
private function variableDeclarationWithNamespace(): VariableDeclaration
{
$start = $this->scanner->getPosition();
$namespace = $this->identifier();
$this->scanner->expectChar('.');
return $this->variableDeclarationWithoutNamespace($namespace, $start);
}
/**
* Consumes a variable declaration.
*/
protected function variableDeclarationWithoutNamespace(?string $namespace = null, ?int $start = null): VariableDeclaration
{
$precedingComment = $this->lastSilentComment;
$this->lastSilentComment = null;
$start = $start ?? $this->scanner->getPosition();
$name = $this->variableName();
if ($namespace !== null) {
$this->assertPublic($name, function () use ($start) {
return $this->scanner->spanFrom($start);
});
}
$this->whitespace();
$this->scanner->expectChar(':');
$this->whitespace();
$value = $this->expression();
$guarded = false;
$global = false;
$flagStart = $this->scanner->getPosition();
while ($this->scanner->scanChar('!')) {
$flag = $this->identifier();
if ($flag === 'default') {
$guarded = true;
} elseif ($flag === 'global') {
if ($namespace !== null) {
$this->error("!global isn't allowed for variables in other modules.", $this->scanner->spanFrom($flagStart));
}
$global = true;
} else {
$this->error('Invalid flag name.', $this->scanner->spanFrom($flagStart));
}
$this->whitespace();
$flagStart = $this->scanner->getPosition();
}
$this->expectStatementSeparator('variable declaration');
// TODO remove this when implementing modules
if ($namespace !== null) {
$this->error('Sass modules are not implemented yet.', $this->scanner->spanFrom($start));
}
$declaration = new VariableDeclaration($name, $value, $this->scanner->spanFrom($start), $namespace, $guarded, $global, $precedingComment);
if ($global && !isset($this->globalVariables[$name])) {
$this->globalVariables[$name] = $declaration;
}
return $declaration;
}
private function variableDeclarationOrStyleRule(): Statement
{
if ($this->isPlainCss()) {
return $this->styleRule();
}
if (!$this->lookingAtIdentifier()) {
return $this->styleRule();
}
$start = $this->scanner->getPosition();
$variableOrInterpolation = $this->variableDeclarationOrInterpolation();
if ($variableOrInterpolation instanceof VariableDeclaration) {
return $variableOrInterpolation;
}
$buffer = new InterpolationBuffer();
$buffer->addInterpolation($variableOrInterpolation);
return $this->styleRule($buffer, $start);
}
/**
* Consumes a {@see VariableDeclaration}, a {@see Declaration}, or a {@see StyleRule}.
*
* @throws FormatException
*/
private function declarationOrStyleRule(): Statement
{
if ($this->isPlainCss() && $this->inStyleRule && !$this->inUnknownAtRule) {
return $this->propertyOrVariableDeclaration();
}
$start = $this->scanner->getPosition();
$declarationBuffer = $this->declarationOrBuffer();
if ($declarationBuffer instanceof Statement) {
return $declarationBuffer;
}
return $this->styleRule($declarationBuffer, $start);
}
/**
* Tries to parse a variable or property declaration, and returns the value
* parsed so far if it fails.
*
* This can return either an {@see InterpolationBuffer}, indicating that it
* couldn't consume a declaration and that selector parsing should be
* attempted; or it can return a {@see Declaration} or a {@see VariableDeclaration},
* indicating that it successfully consumed a declaration.
*
* @return Statement|InterpolationBuffer
*/
private function declarationOrBuffer()
{
$start = $this->scanner->getPosition();
$nameBuffer = new InterpolationBuffer();
$first = $this->scanner->peekChar();
$startsWithPunctuation = false;
// Allow the "*prop: val", ":prop: val", "#prop: val", and ".prop: val"
// hacks.
if ($first === ':' || $first === '*' || $first === '.' || ($first === '#' && $this->scanner->peekChar(1) !== '{')) {
$startsWithPunctuation = true;
$nameBuffer->write($this->scanner->readChar());
$nameBuffer->write($this->rawText([$this, 'whitespace']));
}
if (!$this->lookingAtInterpolatedIdentifier()) {
return $nameBuffer;
}
$variableOrInterpolation = $startsWithPunctuation ? $this->interpolatedIdentifier() : $this->variableDeclarationOrInterpolation();
if ($variableOrInterpolation instanceof VariableDeclaration) {
return $variableOrInterpolation;
}
$nameBuffer->addInterpolation($variableOrInterpolation);
$this->isUseAllowed = false;
if ($this->scanner->matches('/*')) {
$nameBuffer->write($this->rawText([$this, 'loudComment']));
}
$midBuffer = $this->rawText([$this, 'whitespace']);
$beforeColon = $this->scanner->getPosition();
if (!$this->scanner->scanChar(':')) {
if ($midBuffer !== '') {
$nameBuffer->write(' ');
}
return $nameBuffer;
}
$midBuffer .= ':';
// Parse custom properties as declarations no matter what.
$name = $nameBuffer->buildInterpolation($this->scanner->spanFrom($start, $beforeColon));
if (0 === strpos($name->getInitialPlain(), '--')) {
$value = new StringExpression($this->interpolatedDeclarationValue());
$this->expectStatementSeparator('custom property');
return Declaration::create($name, $value, $this->scanner->spanFrom($start));
}
if ($this->scanner->scanChar(':')) {
$nameBuffer->write($midBuffer);
$nameBuffer->write(':');
return $nameBuffer;
}
if ($this->isIndented() && $this->lookingAtInterpolatedIdentifier()) {
$nameBuffer->write($midBuffer);
return $nameBuffer;
}
$postColonWhitespace = $this->rawText([$this, 'whitespace']);
if ($this->lookingAtChildren()) {
return $this->withChildren($this->declarationChildCallable, $start, function (array $children, FileSpan $span) use ($name) {
return Declaration::nested($name, $children, $span);
});
}
$midBuffer .= $postColonWhitespace;
$couldBeSelector = $postColonWhitespace === '' && $this->lookingAtInterpolatedIdentifier();
$beforeDeclaration = $this->scanner->getPosition();
try {
$value = $this->expression();
if ($this->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) {
$this->expectStatementSeparator();
}
} elseif (!$this->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.
$this->expectStatementSeparator();
}
} catch (FormatException $e) {
if (!$couldBeSelector) {
throw $e;
}
// If the value would be followed by a semicolon, it's definitely supposed
// to be a property, not a selector.
$this->scanner->setPosition($beforeDeclaration);
$additional = $this->almostAnyValue();
if (!$this->isIndented() && $this->scanner->peekChar() === ';') {
throw $e;
}
$nameBuffer->write($midBuffer);
$nameBuffer->addInterpolation($additional);
return $nameBuffer;
}
if ($this->lookingAtChildren()) {
return $this->withChildren($this->declarationChildCallable, $start, function (array $children, FileSpan $span) use ($name, $value) {
return Declaration::nested($name, $children, $span, $value);
});
}
$this->expectStatementSeparator();
return Declaration::create($name, $value, $this->scanner->spanFrom($start));
}
/**
* Tries to parse a namespaced {@see VariableDeclaration}, and returns the value
* parsed so far if it fails.
*
* This can return either an {@see 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 {@see VariableDeclaration},
* indicating that it successfully consumed a variable declaration.
*
* @return Interpolation|VariableDeclaration
*/
private function variableDeclarationOrInterpolation()
{
if (!$this->lookingAtIdentifier()) {
return $this->interpolatedIdentifier();
}
$start = $this->scanner->getPosition();
$identifier = $this->identifier();
if ($this->scanner->matches('.$')) {
$this->scanner->readChar();
return $this->variableDeclarationWithoutNamespace($identifier, $start);
}
$buffer = new InterpolationBuffer();
$buffer->write($identifier);
// Parse the rest of an interpolated identifier if one exists, so callers
// don't have to.
if ($this->lookingAtInterpolatedIdentifierBody()) {
$buffer->addInterpolation($this->interpolatedIdentifier());
}
return $buffer->buildInterpolation($this->scanner->spanFrom($start));
}
/**
* Consumes a StyleRule
*/
private function styleRule(?InterpolationBuffer $buffer = null, ?int $start = null): StyleRule
{
$start = $start ?? $this->scanner->getPosition();
$interpolation = $this->styleRuleSelector();
if ($buffer !== null) {
$buffer->addInterpolation($interpolation);
$interpolation = $buffer->buildInterpolation($this->scanner->spanFrom($start));
}
if (!$interpolation->getContents()) {
$this->scanner->error('expected "}".');
}
$wasInStyleRule = $this->inStyleRule;
$this->inStyleRule = true;
return $this->withChildren($this->statementCallable, $start, function (array $children) use ($wasInStyleRule, $start, $interpolation) {
$this->inStyleRule = $wasInStyleRule;
return new StyleRule($interpolation, $children, $this->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,
* {@see declarationOrStyleRule} is used instead.
*
* If $parseCustomProperties is `true`, properties that begin with `--` will
* be parsed using custom property parsing rules.
*/
private function propertyOrVariableDeclaration(bool $parseCustomProperties = true): Statement
{
$start = $this->scanner->getPosition();
// Allow the "*prop: val", ":prop: val", "#prop: val", and ".prop: val"
// hacks.
$first = $this->scanner->peekChar();
if ($first === ':' || $first === '*' || $first === '.' || ($first === '#' && $this->scanner->peekChar(1) !== '{')) {
$nameBuffer = new InterpolationBuffer();
$nameBuffer->write($this->scanner->readChar());
$nameBuffer->write($this->rawText([$this, 'whitespace']));
$nameBuffer->addInterpolation($this->interpolatedIdentifier());
$name = $nameBuffer->buildInterpolation($this->scanner->spanFrom($start));
} elseif (!$this->isPlainCss()) {
$variableOrInterpolation = $this->variableDeclarationOrInterpolation();
if ($variableOrInterpolation instanceof VariableDeclaration) {
return $variableOrInterpolation;
}
$name = $variableOrInterpolation;
} else {
$name = $this->interpolatedIdentifier();
}
$this->whitespace();
$this->scanner->expectChar(':');
if ($parseCustomProperties && 0 === strpos($name->getInitialPlain(), '--')) {
$value = new StringExpression($this->interpolatedDeclarationValue());
$this->expectStatementSeparator('custom property');
return Declaration::create($name, $value, $this->scanner->spanFrom($start));
}
$this->whitespace();
if ($this->lookingAtChildren()) {
if ($this->isPlainCss()) {
$this->scanner->error("Nested declarations aren't allowed in plain CSS.");
}
return $this->withChildren($this->declarationChildCallable, $start, function (array $children, FileSpan $span) use ($name) {
return Declaration::nested($name, $children, $span);
});
}
$value = $this->expression();
if ($this->lookingAtChildren()) {
if ($this->isPlainCss()) {
$this->scanner->error("Nested declarations aren't allowed in plain CSS.");
}
return $this->withChildren($this->declarationChildCallable, $start, function (array $children, FileSpan $span) use ($name, $value) {
return Declaration::nested($name, $children, $span, $value);
});
}
$this->expectStatementSeparator();
return Declaration::create($name, $value, $this->scanner->spanFrom($start));
}
/**
* Consumes a statement that's allowed within a declaration.
*/
private function declarationChild(): Statement
{
if ($this->scanner->peekChar() === '@') {
return $this->declarationAtRule();
}
return $this->propertyOrVariableDeclaration(false);
}
/**
* 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.
*
* @param callable(): Statement $child
*/
protected function atRule(callable $child, bool $root = false): Statement
{
$start = $this->scanner->getPosition();
$this->scanner->expectChar('@', '@-rule');
$name = $this->interpolatedIdentifier();
$this->whitespace();
$wasUseAllowed = $this->isUseAllowed;
$this->isUseAllowed = false;
switch ($name->getAsPlain()) {
case 'at-root':
return $this->atRootRule($start);
case 'content':
return $this->contentRule($start);
case 'debug':
return $this->debugRule($start);
case 'each':
return $this->eachRule($start, $child);
case 'else':
$this->disallowedAtRule($start);
case 'error':
return $this->errorRule($start);
case 'extend':
return $this->extendRule($start);
case 'for':
return $this->forRule($start, $child);
case 'forward':
$this->isUseAllowed = $wasUseAllowed;
if (!$root) {
$this->disallowedAtRule($start);
}
// TODO remove this when implementing modules
$this->error('Sass modules are not implemented yet.', $this->scanner->spanFrom($start));
case 'function':
return $this->functionRule($start);
case 'if':
return $this->ifRule($start, $child);
case 'import':
return $this->importRule($start);
case 'include':
return $this->includeRule($start);
case 'media':
return $this->mediaRule($start);
case 'mixin':
return $this->mixinRule($start);
case '-moz-document':
return $this->mozDocumentRule($start, $name);
case 'return':
$this->disallowedAtRule($start);
case 'supports':
return $this->supportsRule($start);
case 'use':
$this->isUseAllowed = $wasUseAllowed;
if (!$root) {
$this->disallowedAtRule($start);
}
// TODO remove this when implementing modules
$this->error('Sass modules are not implemented yet.', $this->scanner->spanFrom($start));
case 'warn':
return $this->warnRule($start);
case 'while':
return $this->whileRule($start, $child);
default:
return $this->unknownAtRule($start, $name);
}
}
/**
* Consumes an at-rule allowed within a property declaration.
*/
private function declarationAtRule(): Statement
{
$start = $this->scanner->getPosition();
$name = $this->plainAtRuleName();
switch ($name) {
case 'content':
return $this->contentRule($start);
case 'debug':
return $this->debugRule($start);
case 'each':
return $this->eachRule($start, $this->declarationChildCallable);
case 'else':
$this->disallowedAtRule($start);
case 'error':
return $this->errorRule($start);
case 'for':
return $this->forRule($start, $this->declarationChildCallable);
case 'if':
return $this->ifRule($start, $this->declarationChildCallable);
case 'include':
return $this->includeRule($start);
case 'warn':
return $this->warnRule($start);
case 'while':
return $this->whileRule($start, $this->declarationChildCallable);
default:
$this->disallowedAtRule($start);
}
}
/**
* Consumes a statement allowed within a function.
*/
private function functionChild(): Statement
{
if ($this->scanner->peekChar() !== '@') {
$start = $this->scanner->getPosition();
try {
return $this->variableDeclarationWithNamespace();
} catch (FormatException $variableDeclarationError) {
// TODO remove this when implementing modules
if ($variableDeclarationError->getMessage() === 'Sass modules are not implemented yet.') {
throw $variableDeclarationError;
}
$this->scanner->setPosition($start);
// 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.
try {
$statement = $this->declarationOrStyleRule();
} catch (FormatException $e) {
throw $variableDeclarationError;
}
$this->error('@function rules may not contain ' . ($statement instanceof StyleRule ? 'style rules.' : 'declarations.'), $statement->getSpan());
}
}
$start = $this->scanner->getPosition();
switch ($this->plainAtRuleName()) {
case 'debug':
return $this->debugRule($start);
case 'each':
return $this->eachRule($start, $this->functionChildCallable);
case 'else':
$this->disallowedAtRule($start);
case 'error':
return $this->errorRule($start);
case 'for':
return $this->forRule($start, $this->functionChildCallable);
case 'if':
return $this->ifRule($start, $this->functionChildCallable);
case 'return':
return $this->returnRule($start);
case 'warn':
return $this->warnRule($start);
case 'while':
return $this->whileRule($start, $this->functionChildCallable);
default:
$this->disallowedAtRule($start);
}
}
/**
* Consumes an at-rule's name, with interpolation disallowed.
*/
private function plainAtRuleName(): string
{
$this->scanner->expectChar('@', '@-rule');
$name = $this->identifier();
$this->whitespace();
return $name;
}
/**
* Consumes an `@at-root` rule.
*
* $start should point before the `@`.
*/
private function atRootRule(int $start): AtRootRule
{
if ($this->scanner->peekChar() === '(') {
$query = $this->atRootQuery();
$this->whitespace();
return $this->withChildren($this->statementCallable, $start, function (array $children, FileSpan $span) use ($query) {
return new AtRootRule($children, $span, $query);
});
}
if ($this->lookingAtChildren()) {
return $this->withChildren($this->statementCallable, $start, function (array $children, FileSpan $span) {
return new AtRootRule($children, $span);
});
}
$child = $this->styleRule();
return new AtRootRule([$child], $this->scanner->spanFrom($start));
}
/**
* Consumes a query expression of the form `(foo: bar)`.
*/
private function atRootQuery(): Interpolation
{
if ($this->scanner->peekChar() === '#') {
$interpolation = $this->singleInterpolation();
return new Interpolation([$interpolation], $interpolation->getSpan());
}
$start = $this->scanner->getPosition();
$buffer = new InterpolationBuffer();
$this->scanner->expectChar('(');
$buffer->write('(');
$this->whitespace();
$buffer->add($this->expression());
if ($this->scanner->scanChar(':')) {
$this->whitespace();
$buffer->write(': ');
$buffer->add($this->expression());
}
$this->scanner->expectChar(')');
$this->whitespace();
$buffer->write(')');
return $buffer->buildInterpolation($this->scanner->spanFrom($start));
}
/**
* Consumes a `@content` rule.
*
* $start should point before the `@`.
*/
private function contentRule(int $start): ContentRule
{
if (!$this->inMixin) {
$this->error('@content is only allowed within mixin declarations.', $this->scanner->spanFrom($start));
}
$this->whitespace();
$arguments = $this->scanner->peekChar() === '(' ? $this->argumentInvocation(true) : ArgumentInvocation::createEmpty($this->scanner->getEmptySpan());
$this->expectStatementSeparator('@content rule');
return new ContentRule($arguments, $this->scanner->spanFrom($start));
}
/**
* Consumes a `@debug` rule.
*
* $start should point before the `@`.
*/
private function debugRule(int $start): DebugRule
{
$value = $this->expression();
$this->expectStatementSeparator('@debug rule');
return new DebugRule($value, $this->scanner->spanFrom($start));
}
/**
* Consumes a `@each` rule.
*
* $start should point before the `@`. $child is called to consume any
* children that are specifically allowed in the caller's context.
*
* @param callable(): Statement $child
*/
private function eachRule(int $start, callable $child): EachRule
{
$wasInControlDirective = $this->inControlDirective;
$this->inControlDirective = true;
$variables = [$this->variableName()];
$this->whitespace();
while ($this->scanner->scanChar(',')) {
$this->whitespace();
$variables[] = $this->variableName();