5 * @copyright 2012-2019 Leaf Corcoran
7 * @license http://opensource.org/licenses/MIT MIT
9 * @link http://scssphp.github.io/scssphp
12 namespace ScssPhp\ScssPhp
;
14 use ScssPhp\ScssPhp\Block
;
15 use ScssPhp\ScssPhp\Cache
;
16 use ScssPhp\ScssPhp\Compiler
;
17 use ScssPhp\ScssPhp\Exception\ParserException
;
18 use ScssPhp\ScssPhp\Node
;
19 use ScssPhp\ScssPhp\Type
;
24 * @author Leaf Corcoran <leafot@gmail.com>
28 const SOURCE_INDEX
= -1;
29 const SOURCE_LINE
= -2;
30 const SOURCE_COLUMN
= -3;
35 protected static $precedence = [
53 protected static $commentPattern;
54 protected static $operatorPattern;
55 protected static $whitePattern;
61 private $sourcePositions;
66 private $eatWhiteDefault;
67 private $discardComments;
71 private $patternModifiers;
72 private $commentsSeen;
79 * @param string $sourceName
80 * @param integer $sourceIndex
81 * @param string $encoding
82 * @param \ScssPhp\ScssPhp\Cache $cache
84 public function __construct($sourceName, $sourceIndex = 0, $encoding = 'utf-8', $cache = null)
86 $this->sourceName
= $sourceName ?
: '(stdin)';
87 $this->sourceIndex
= $sourceIndex;
88 $this->charset
= null;
89 $this->utf8
= ! $encoding ||
strtolower($encoding) === 'utf-8';
90 $this->patternModifiers
= $this->utf8 ?
'Aisu' : 'Ais';
91 $this->commentsSeen
= [];
92 $this->discardComments
= false;
94 if (empty(static::$operatorPattern)) {
95 static::$operatorPattern = '([*\/%+-]|[!=]\=|\>\=?|\<\=\>|\<\=?|and|or)';
97 $commentSingle = '\/\/';
98 $commentMultiLeft = '\/\*';
99 $commentMultiRight = '\*\/';
101 static::$commentPattern = $commentMultiLeft . '.*?' . $commentMultiRight;
102 static::$whitePattern = $this->utf8
103 ?
'/' . $commentSingle . '[^\n]*\s*|(' . static::$commentPattern . ')\s*|\s+/AisuS'
104 : '/' . $commentSingle . '[^\n]*\s*|(' . static::$commentPattern . ')\s*|\s+/AisS';
108 $this->cache
= $cache;
113 * Get source file name
119 public function getSourceName()
121 return $this->sourceName
;
131 * @throws \ScssPhp\ScssPhp\Exception\ParserException
133 public function throwParseError($msg = 'parse error')
135 list($line, $column) = $this->getSourcePosition($this->count
);
137 $loc = empty($this->sourceName
)
138 ?
"line: $line, column: $column"
139 : "$this->sourceName on line $line, at column $column";
141 if ($this->peek("(.*?)(\n|$)", $m, $this->count
)) {
142 throw new ParserException("$msg: failed at `$m[1]` $loc");
145 throw new ParserException("$msg: $loc");
153 * @param string $buffer
155 * @return \ScssPhp\ScssPhp\Block
157 public function parse($buffer)
160 $cacheKey = $this->sourceName
. ":" . md5($buffer);
162 'charset' => $this->charset
,
163 'utf8' => $this->utf8
,
165 $v = $this->cache
->getCache("parse", $cacheKey, $parseOptions);
172 // strip BOM (byte order marker)
173 if (substr($buffer, 0, 3) === "\xef\xbb\xbf") {
174 $buffer = substr($buffer, 3);
177 $this->buffer
= rtrim($buffer, "\x00..\x1f");
180 $this->inParens
= false;
181 $this->eatWhiteDefault
= true;
183 $this->saveEncoding();
184 $this->extractLineNumbers($buffer);
186 $this->pushBlock(null); // root block
188 $this->pushBlock(null);
191 while ($this->parseChunk()) {
195 if ($this->count
!== strlen($this->buffer
)) {
196 $this->throwParseError();
199 if (! empty($this->env
->parent
)) {
200 $this->throwParseError('unclosed block');
203 if ($this->charset
) {
204 array_unshift($this->env
->children
, $this->charset
);
207 $this->restoreEncoding();
210 $this->cache
->setCache("parse", $cacheKey, $this->env
, $parseOptions);
217 * Parse a value or value list
221 * @param string $buffer
222 * @param string|array $out
226 public function parseValue($buffer, &$out)
230 $this->inParens
= false;
231 $this->eatWhiteDefault
= true;
232 $this->buffer
= (string) $buffer;
234 $this->saveEncoding();
236 $list = $this->valueList($out);
238 $this->restoreEncoding();
244 * Parse a selector or selector list
248 * @param string $buffer
249 * @param string|array $out
253 public function parseSelector($buffer, &$out)
257 $this->inParens
= false;
258 $this->eatWhiteDefault
= true;
259 $this->buffer
= (string) $buffer;
261 $this->saveEncoding();
263 $selector = $this->selectors($out);
265 $this->restoreEncoding();
271 * Parse a media Query
275 * @param string $buffer
276 * @param string|array $out
280 public function parseMediaQueryList($buffer, &$out)
284 $this->inParens
= false;
285 $this->eatWhiteDefault
= true;
286 $this->buffer
= (string) $buffer;
288 $this->saveEncoding();
290 $isMediaQuery = $this->mediaQueryList($out);
292 $this->restoreEncoding();
294 return $isMediaQuery;
298 * Parse a single chunk off the head of the buffer and append it to the
299 * current parse environment.
301 * Returns false when the buffer is empty, or when there is an error.
303 * This function is called repeatedly until the entire document is
306 * This parser is most similar to a recursive descent parser. Single
307 * functions represent discrete grammatical rules for the language, and
308 * they are able to capture the text that represents those rules.
310 * Consider the function Compiler::keyword(). (All parse functions are
311 * structured the same.)
313 * The function takes a single reference argument. When calling the
314 * function it will attempt to match a keyword on the head of the buffer.
315 * If it is successful, it will place the keyword in the referenced
316 * argument, advance the position in the buffer, and return true. If it
317 * fails then it won't advance the buffer and it will return false.
319 * All of these parse functions are powered by Compiler::match(), which behaves
320 * the same way, but takes a literal regular expression. Sometimes it is
321 * more convenient to use match instead of creating a new function.
323 * Because of the format of the functions, to parse an entire string of
324 * grammatical rules, you can chain them together using &&.
326 * But, if some of the rules in the chain succeed before one fails, then
327 * the buffer position will be left at an invalid state. In order to
328 * avoid this, Compiler::seek() is used to remember and set buffer positions.
330 * Before parsing a chain, use $s = $this->count to remember the current
331 * position into $s. Then if a chain fails, use $this->seek($s) to
332 * go back where we started.
336 protected function parseChunk()
341 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] === '@') {
342 if ($this->literal('@at-root', 8) &&
343 ($this->selectors($selector) ||
true) &&
344 ($this->map($with) ||
true) &&
345 (($this->matchChar('(')
346 && $this->interpolation($with)
347 && $this->matchChar(')')) ||
true) &&
348 $this->matchChar('{', false)
350 $atRoot = $this->pushSpecialBlock(Type
::T_AT_ROOT
, $s);
351 $atRoot->selector
= $selector;
352 $atRoot->with
= $with;
359 if ($this->literal('@media', 6) && $this->mediaQueryList($mediaQueryList) && $this->matchChar('{', false)) {
360 $media = $this->pushSpecialBlock(Type
::T_MEDIA
, $s);
361 $media->queryList
= $mediaQueryList[2];
368 if ($this->literal('@mixin', 6) &&
369 $this->keyword($mixinName) &&
370 ($this->argumentDef($args) ||
true) &&
371 $this->matchChar('{', false)
373 $mixin = $this->pushSpecialBlock(Type
::T_MIXIN
, $s);
374 $mixin->name
= $mixinName;
375 $mixin->args
= $args;
382 if ($this->literal('@include', 8) &&
383 $this->keyword($mixinName) &&
384 ($this->matchChar('(') &&
385 ($this->argValues($argValues) ||
true) &&
386 $this->matchChar(')') ||
true) &&
388 ($this->literal('using', 5) &&
389 $this->argumentDef($argUsing) &&
390 ($this->end() ||
$this->matchChar('{') && $hasBlock = true)) ||
391 $this->matchChar('{') && $hasBlock = true)
396 isset($argValues) ?
$argValues : null,
398 isset($argUsing) ?
$argUsing : null
401 if (! empty($hasBlock)) {
402 $include = $this->pushSpecialBlock(Type
::T_INCLUDE
, $s);
403 $include->child
= $child;
405 $this->append($child, $s);
413 if ($this->literal('@scssphp-import-once', 20) &&
414 $this->valueList($importPath) &&
417 $this->append([Type
::T_SCSSPHP_IMPORT_ONCE
, $importPath], $s);
424 if ($this->literal('@import', 7) &&
425 $this->valueList($importPath) &&
428 $this->append([Type
::T_IMPORT
, $importPath], $s);
435 if ($this->literal('@import', 7) &&
436 $this->url($importPath) &&
439 $this->append([Type
::T_IMPORT
, $importPath], $s);
446 if ($this->literal('@extend', 7) &&
447 $this->selectors($selectors) &&
451 $optional = $this->stripOptionalFlag($selectors);
452 $this->append([Type
::T_EXTEND
, $selectors, $optional], $s);
459 if ($this->literal('@function', 9) &&
460 $this->keyword($fnName) &&
461 $this->argumentDef($args) &&
462 $this->matchChar('{', false)
464 $func = $this->pushSpecialBlock(Type
::T_FUNCTION
, $s);
465 $func->name
= $fnName;
473 if ($this->literal('@break', 6) && $this->end()) {
474 $this->append([Type
::T_BREAK
], $s);
481 if ($this->literal('@continue', 9) && $this->end()) {
482 $this->append([Type
::T_CONTINUE
], $s);
489 if ($this->literal('@return', 7) && ($this->valueList($retVal) ||
true) && $this->end()) {
490 $this->append([Type
::T_RETURN
, isset($retVal) ?
$retVal : [Type
::T_NULL
]], $s);
497 if ($this->literal('@each', 5) &&
498 $this->genericList($varNames, 'variable', ',', false) &&
499 $this->literal('in', 2) &&
500 $this->valueList($list) &&
501 $this->matchChar('{', false)
503 $each = $this->pushSpecialBlock(Type
::T_EACH
, $s);
505 foreach ($varNames[2] as $varName) {
506 $each->vars
[] = $varName[1];
516 if ($this->literal('@while', 6) &&
517 $this->expression($cond) &&
518 $this->matchChar('{', false)
520 $while = $this->pushSpecialBlock(Type
::T_WHILE
, $s);
521 $while->cond
= $cond;
528 if ($this->literal('@for', 4) &&
529 $this->variable($varName) &&
530 $this->literal('from', 4) &&
531 $this->expression($start) &&
532 ($this->literal('through', 7) ||
533 ($forUntil = true && $this->literal('to', 2))) &&
534 $this->expression($end) &&
535 $this->matchChar('{', false)
537 $for = $this->pushSpecialBlock(Type
::T_FOR
, $s);
538 $for->var = $varName[1];
539 $for->start
= $start;
541 $for->until
= isset($forUntil);
548 if ($this->literal('@if', 3) && $this->valueList($cond) && $this->matchChar('{', false)) {
549 $if = $this->pushSpecialBlock(Type
::T_IF
, $s);
550 while ($cond[0] === Type
::T_LIST
551 && !empty($cond['enclosing'])
552 && $cond['enclosing'] === 'parent'
553 && count($cond[2]) == 1) {
554 $cond = reset($cond[2]);
564 if ($this->literal('@debug', 6) &&
565 $this->valueList($value) &&
568 $this->append([Type
::T_DEBUG
, $value], $s);
575 if ($this->literal('@warn', 5) &&
576 $this->valueList($value) &&
579 $this->append([Type
::T_WARN
, $value], $s);
586 if ($this->literal('@error', 6) &&
587 $this->valueList($value) &&
590 $this->append([Type
::T_ERROR
, $value], $s);
597 #if ($this->literal('@content', 8))
599 if ($this->literal('@content', 8) &&
601 $this->matchChar('(') &&
602 $this->argValues($argContent) &&
603 $this->matchChar(')') &&
605 $this->append([Type
::T_MIXIN_CONTENT
, isset($argContent) ?
$argContent : null], $s);
612 $last = $this->last();
614 if (isset($last) && $last[0] === Type
::T_IF
) {
617 if ($this->literal('@else', 5)) {
618 if ($this->matchChar('{', false)) {
619 $else = $this->pushSpecialBlock(Type
::T_ELSE
, $s);
620 } elseif ($this->literal('if', 2) && $this->valueList($cond) && $this->matchChar('{', false)) {
621 $else = $this->pushSpecialBlock(Type
::T_ELSEIF
, $s);
626 $else->dontAppend
= true;
627 $if->cases
[] = $else;
636 // only retain the first @charset directive encountered
637 if ($this->literal('@charset', 8) &&
638 $this->valueList($charset) &&
641 if (! isset($this->charset
)) {
642 $statement = [Type
::T_CHARSET
, $charset];
644 list($line, $column) = $this->getSourcePosition($s);
646 $statement[static::SOURCE_LINE
] = $line;
647 $statement[static::SOURCE_COLUMN
] = $column;
648 $statement[static::SOURCE_INDEX
] = $this->sourceIndex
;
650 $this->charset
= $statement;
658 if ($this->literal('@supports', 9) &&
659 ($t1=$this->supportsQuery($supportQuery)) &&
660 ($t2=$this->matchChar('{', false))
662 $directive = $this->pushSpecialBlock(Type
::T_DIRECTIVE
, $s);
663 $directive->name
= 'supports';
664 $directive->value
= $supportQuery;
671 // doesn't match built in directive, do generic one
672 if ($this->matchChar('@', false) &&
673 $this->keyword($dirName) &&
674 ($this->variable($dirValue) ||
$this->openString('{', $dirValue) ||
true) &&
675 $this->matchChar('{', false)
677 if ($dirName === 'media') {
678 $directive = $this->pushSpecialBlock(Type
::T_MEDIA
, $s);
680 $directive = $this->pushSpecialBlock(Type
::T_DIRECTIVE
, $s);
681 $directive->name
= $dirName;
684 if (isset($dirValue)) {
685 $directive->value
= $dirValue;
693 // maybe it's a generic blockless directive
694 if ($this->matchChar('@', false) &&
695 $this->keyword($dirName) &&
696 $this->valueList($dirValue) &&
699 $this->append([Type
::T_DIRECTIVE
, [$dirName, $dirValue]], $s);
710 // captures most properties before having to parse a selector
711 if ($this->keyword($name, false) &&
712 $this->literal(': ', 2) &&
713 $this->valueList($value) &&
716 $name = [Type
::T_STRING
, '', [$name]];
717 $this->append([Type
::T_ASSIGN
, $name, $value], $s);
725 if ($this->variable($name) &&
726 $this->matchChar(':') &&
727 $this->valueList($value) &&
731 $assignmentFlags = $this->stripAssignmentFlags($value);
732 $this->append([Type
::T_ASSIGN
, $name, $value, $assignmentFlags], $s);
740 if ($this->literal('-->', 3)) {
745 if ($this->selectors($selectors) && $this->matchChar('{', false)) {
746 $this->pushBlock($selectors, $s);
748 if ($this->eatWhiteDefault
) {
750 $this->append(null); // collect comments at the beginning if needed
758 // property assign, or nested assign
759 if ($this->propertyName($name) && $this->matchChar(':')) {
760 $foundSomething = false;
762 if ($this->valueList($value)) {
763 if (empty($this->env
->parent
)) {
764 $this->throwParseError('expected "{"');
767 $this->append([Type
::T_ASSIGN
, $name, $value], $s);
768 $foundSomething = true;
771 if ($this->matchChar('{', false)) {
772 $propBlock = $this->pushSpecialBlock(Type
::T_NESTED_PROPERTY
, $s);
773 $propBlock->prefix
= $name;
774 $propBlock->hasValue
= $foundSomething;
776 $foundSomething = true;
777 } elseif ($foundSomething) {
778 $foundSomething = $this->end();
781 if ($foundSomething) {
789 if ($this->matchChar('}', false)) {
790 $block = $this->popBlock();
792 if (! isset($block->type
) ||
$block->type
!== Type
::T_IF
) {
793 if ($this->env
->parent
) {
794 $this->append(null); // collect comments before next statement if needed
798 if (isset($block->type
) && $block->type
=== Type
::T_INCLUDE
) {
799 $include = $block->child
;
800 unset($block->child
);
801 $include[3] = $block;
802 $this->append($include, $s);
803 } elseif (empty($block->dontAppend
)) {
804 $type = isset($block->type
) ?
$block->type
: Type
::T_BLOCK
;
805 $this->append([$type, $block], $s);
808 // collect comments just after the block closing if needed
809 if ($this->eatWhiteDefault
) {
812 if ($this->env
->comments
) {
821 if ($this->matchChar(';') ||
822 $this->literal('<!--', 4)
831 * Push block onto parse tree
833 * @param array $selectors
834 * @param integer $pos
836 * @return \ScssPhp\ScssPhp\Block
838 protected function pushBlock($selectors, $pos = 0)
840 list($line, $column) = $this->getSourcePosition($pos);
843 $b->sourceName
= $this->sourceName
;
844 $b->sourceLine
= $line;
845 $b->sourceColumn
= $column;
846 $b->sourceIndex
= $this->sourceIndex
;
847 $b->selectors
= $selectors;
849 $b->parent
= $this->env
;
853 } elseif (empty($this->env
->children
)) {
854 $this->env
->children
= $this->env
->comments
;
856 $this->env
->comments
= [];
858 $b->children
= $this->env
->comments
;
859 $this->env
->comments
= [];
864 // collect comments at the beginning of a block if needed
865 if ($this->eatWhiteDefault
) {
868 if ($this->env
->comments
) {
877 * Push special (named) block onto parse tree
879 * @param string $type
880 * @param integer $pos
882 * @return \ScssPhp\ScssPhp\Block
884 protected function pushSpecialBlock($type, $pos)
886 $block = $this->pushBlock(null, $pos);
887 $block->type
= $type;
893 * Pop scope and return last block
895 * @return \ScssPhp\ScssPhp\Block
899 protected function popBlock()
902 // collect comments ending just before of a block closing
903 if ($this->env
->comments
) {
910 if (empty($block->parent
)) {
911 $this->throwParseError('unexpected }');
914 if ($block->type
== Type
::T_AT_ROOT
) {
915 // keeps the parent in case of self selector &
916 $block->selfParent
= $block->parent
;
919 $this->env
= $block->parent
;
921 unset($block->parent
);
929 * @param string $regex
931 * @param integer $from
935 protected function peek($regex, &$out, $from = null)
937 if (! isset($from)) {
938 $from = $this->count
;
941 $r = '/' . $regex . '/' . $this->patternModifiers
;
942 $result = preg_match($r, $this->buffer
, $out, null, $from);
948 * Seek to position in input stream (or return current position in input stream)
950 * @param integer $where
952 protected function seek($where)
954 $this->count
= $where;
958 * Match string looking for either ending delim, escape, or string interpolation
960 * {@internal This is a workaround for preg_match's 250K string match limit. }}
962 * @param array $m Matches (passed by reference)
963 * @param string $delim Delimeter
965 * @return boolean True if match; false otherwise
967 protected function matchString(&$m, $delim)
971 $end = strlen($this->buffer
);
973 // look for either ending delim, escape, or string interpolation
974 foreach (['#{', '\\', $delim] as $lookahead) {
975 $pos = strpos($this->buffer
, $lookahead, $this->count
);
977 if ($pos !== false && $pos < $end) {
983 if (! isset($token)) {
987 $match = substr($this->buffer
, $this->count
, $end - $this->count
);
993 $this->count
= $end +
strlen($token);
999 * Try to match something on head of buffer
1001 * @param string $regex
1003 * @param boolean $eatWhitespace
1007 protected function match($regex, &$out, $eatWhitespace = null)
1009 $r = '/' . $regex . '/' . $this->patternModifiers
;
1011 if (! preg_match($r, $this->buffer
, $out, null, $this->count
)) {
1015 $this->count +
= strlen($out[0]);
1017 if (! isset($eatWhitespace)) {
1018 $eatWhitespace = $this->eatWhiteDefault
;
1021 if ($eatWhitespace) {
1022 $this->whitespace();
1029 * Match a single string
1031 * @param string $char
1032 * @param boolean $eatWhitespace
1036 protected function matchChar($char, $eatWhitespace = null)
1038 if (! isset($this->buffer
[$this->count
]) ||
$this->buffer
[$this->count
] !== $char) {
1044 if (! isset($eatWhitespace)) {
1045 $eatWhitespace = $this->eatWhiteDefault
;
1048 if ($eatWhitespace) {
1049 $this->whitespace();
1056 * Match literal string
1058 * @param string $what
1059 * @param integer $len
1060 * @param boolean $eatWhitespace
1064 protected function literal($what, $len, $eatWhitespace = null)
1066 if (strcasecmp(substr($this->buffer
, $this->count
, $len), $what) !== 0) {
1070 $this->count +
= $len;
1072 if (! isset($eatWhitespace)) {
1073 $eatWhitespace = $this->eatWhiteDefault
;
1076 if ($eatWhitespace) {
1077 $this->whitespace();
1084 * Match some whitespace
1088 protected function whitespace()
1092 while (preg_match(static::$whitePattern, $this->buffer
, $m, null, $this->count
)) {
1093 if (isset($m[1]) && empty($this->commentsSeen
[$this->count
])) {
1094 // comment that are kept in the output CSS
1096 $startCommentCount = $this->count
;
1097 $endCommentCount = $this->count +
strlen($m[1]);
1099 // find interpolations in comment
1100 $p = strpos($this->buffer
, '#{', $this->count
);
1102 while ($p !== false && $p < $endCommentCount) {
1103 $c = substr($this->buffer
, $this->count
, $p - $this->count
);
1108 if ($this->interpolation($out)) {
1109 // keep right spaces in the following string part
1111 while ($this->buffer
[$this->count
-1] !== '}') {
1118 $comment[] = [Type
::T_COMMENT
, substr($this->buffer
, $p, $this->count
- $p), $out];
1120 $comment[] = substr($this->buffer
, $this->count
, 2);
1125 $p = strpos($this->buffer
, '#{', $this->count
);
1129 $c = substr($this->buffer
, $this->count
, $endCommentCount - $this->count
);
1132 // single part static comment
1133 $this->appendComment([Type
::T_COMMENT
, $c]);
1136 $staticComment = substr($this->buffer
, $startCommentCount, $endCommentCount - $startCommentCount);
1137 $this->appendComment([Type
::T_COMMENT
, $staticComment, [Type
::T_STRING
, '', $comment]]);
1140 $this->commentsSeen
[$startCommentCount] = true;
1141 $this->count
= $endCommentCount;
1143 // comment that are ignored and not kept in the output css
1144 $this->count +
= strlen($m[0]);
1154 * Append comment to current block
1156 * @param array $comment
1158 protected function appendComment($comment)
1160 if (! $this->discardComments
) {
1161 if ($comment[0] === Type
::T_COMMENT
) {
1162 if (is_string($comment[1])) {
1163 $comment[1] = substr(preg_replace(['/^\s+/m', '/^(.)/m'], ['', ' \1'], $comment[1]), 1);
1165 if (isset($comment[2]) and is_array($comment[2]) and $comment[2][0] === Type
::T_STRING
) {
1166 foreach ($comment[2][2] as $k => $v) {
1167 if (is_string($v)) {
1168 $p = strpos($v, "\n");
1170 $comment[2][2][$k] = substr($v, 0, $p +
1)
1171 . preg_replace(['/^\s+/m', '/^(.)/m'], ['', ' \1'], substr($v, $p+
1));
1178 $this->env
->comments
[] = $comment;
1183 * Append statement to current block
1185 * @param array $statement
1186 * @param integer $pos
1188 protected function append($statement, $pos = null)
1190 if (! is_null($statement)) {
1191 if (! is_null($pos)) {
1192 list($line, $column) = $this->getSourcePosition($pos);
1194 $statement[static::SOURCE_LINE
] = $line;
1195 $statement[static::SOURCE_COLUMN
] = $column;
1196 $statement[static::SOURCE_INDEX
] = $this->sourceIndex
;
1199 $this->env
->children
[] = $statement;
1202 $comments = $this->env
->comments
;
1205 $this->env
->children
= array_merge($this->env
->children
, $comments);
1206 $this->env
->comments
= [];
1211 * Returns last child was appended
1213 * @return array|null
1215 protected function last()
1217 $i = count($this->env
->children
) - 1;
1219 if (isset($this->env
->children
[$i])) {
1220 return $this->env
->children
[$i];
1225 * Parse media query list
1231 protected function mediaQueryList(&$out)
1233 return $this->genericList($out, 'mediaQuery', ',', false);
1243 protected function mediaQuery(&$out)
1245 $expressions = null;
1248 if (($this->literal('only', 4) && ($only = true) ||
$this->literal('not', 3) && ($not = true) ||
true) &&
1249 $this->mixedKeyword($mediaType)
1251 $prop = [Type
::T_MEDIA_TYPE
];
1254 $prop[] = [Type
::T_KEYWORD
, 'only'];
1258 $prop[] = [Type
::T_KEYWORD
, 'not'];
1261 $media = [Type
::T_LIST
, '', []];
1263 foreach ((array) $mediaType as $type) {
1264 if (is_array($type)) {
1265 $media[2][] = $type;
1267 $media[2][] = [Type
::T_KEYWORD
, $type];
1275 if (empty($parts) ||
$this->literal('and', 3)) {
1276 $this->genericList($expressions, 'mediaExpression', 'and', false);
1278 if (is_array($expressions)) {
1279 $parts = array_merge($parts, $expressions[2]);
1289 * Parse supports query
1295 protected function supportsQuery(&$out)
1297 $expressions = null;
1304 if (($this->literal('not', 3) && ($not = true) ||
true) &&
1305 $this->matchChar('(') &&
1306 ($this->expression($property)) &&
1307 $this->literal(': ', 2) &&
1308 $this->valueList($value) &&
1309 $this->matchChar(')')
1311 $support = [Type
::T_STRING
, '', [[Type
::T_KEYWORD
, ($not ?
'not ' : '') . '(']]];
1312 $support[2][] = $property;
1313 $support[2][] = [Type
::T_KEYWORD
, ': '];
1314 $support[2][] = $value;
1315 $support[2][] = [Type
::T_KEYWORD
, ')'];
1317 $parts[] = $support;
1323 if ($this->matchChar('(') &&
1324 $this->supportsQuery($subQuery) &&
1325 $this->matchChar(')')
1327 $parts[] = [Type
::T_STRING
, '', [[Type
::T_KEYWORD
, '('], $subQuery, [Type
::T_KEYWORD
, ')']]];
1333 if ($this->literal('not', 3) &&
1334 $this->supportsQuery($subQuery)
1336 $parts[] = [Type
::T_STRING
, '', [[Type
::T_KEYWORD
, 'not '], $subQuery]];
1342 if ($this->literal('selector(', 9) &&
1343 $this->selector($selector) &&
1344 $this->matchChar(')')
1346 $support = [Type
::T_STRING
, '', [[Type
::T_KEYWORD
, 'selector(']]];
1348 $selectorList = [Type
::T_LIST
, '', []];
1350 foreach ($selector as $sc) {
1351 $compound = [Type
::T_STRING
, '', []];
1353 foreach ($sc as $scp) {
1354 if (is_array($scp)) {
1355 $compound[2][] = $scp;
1357 $compound[2][] = [Type
::T_KEYWORD
, $scp];
1361 $selectorList[2][] = $compound;
1363 $support[2][] = $selectorList;
1364 $support[2][] = [Type
::T_KEYWORD
, ')'];
1365 $parts[] = $support;
1371 if ($this->variable($var) or $this->interpolation($var)) {
1378 if ($this->literal('and', 3) &&
1379 $this->genericList($expressions, 'supportsQuery', ' and', false)) {
1380 array_unshift($expressions[2], [Type
::T_STRING
, '', $parts]);
1382 $parts = [$expressions];
1388 if ($this->literal('or', 2) &&
1389 $this->genericList($expressions, 'supportsQuery', ' or', false)) {
1390 array_unshift($expressions[2], [Type
::T_STRING
, '', $parts]);
1392 $parts = [$expressions];
1398 if (count($parts)) {
1399 if ($this->eatWhiteDefault
) {
1400 $this->whitespace();
1403 $out = [Type
::T_STRING
, '', $parts];
1413 * Parse media expression
1419 protected function mediaExpression(&$out)
1424 if ($this->matchChar('(') &&
1425 $this->expression($feature) &&
1426 ($this->matchChar(':') && $this->expression($value) ||
true) &&
1427 $this->matchChar(')')
1429 $out = [Type
::T_MEDIA_EXPRESSION
, $feature];
1444 * Parse argument values
1450 protected function argValues(&$out)
1452 if ($this->genericList($list, 'argValue', ',', false)) {
1462 * Parse argument value
1468 protected function argValue(&$out)
1474 if (! $this->variable($keyword) ||
! $this->matchChar(':')) {
1480 if ($this->genericList($value, 'expression')) {
1481 $out = [$keyword, $value, false];
1484 if ($this->literal('...', 3)) {
1497 * Parse comma separated value list
1503 protected function valueList(&$out)
1505 $discardComments = $this->discardComments
;
1506 $this->discardComments
= true;
1507 $res = $this->genericList($out, 'spaceList', ',');
1508 $this->discardComments
= $discardComments;
1514 * Parse space separated value list
1520 protected function spaceList(&$out)
1522 return $this->genericList($out, 'expression');
1526 * Parse generic list
1529 * @param callable $parseItem
1530 * @param string $delim
1531 * @param boolean $flatten
1535 protected function genericList(&$out, $parseItem, $delim = '', $flatten = true)
1541 while ($this->$parseItem($value)) {
1542 $trailing_delim = false;
1546 if (! $this->literal($delim, strlen($delim))) {
1549 $trailing_delim = true;
1559 if ($trailing_delim) {
1560 $items[] = [Type
::T_NULL
];
1562 if ($flatten && count($items) === 1) {
1565 $out = [Type
::T_LIST
, $delim, $items];
1575 * @param bool $listOnly
1576 * @param bool $lookForExp
1580 protected function expression(&$out, $listOnly = false, $lookForExp = true)
1583 $discard = $this->discardComments
;
1584 $this->discardComments
= true;
1585 $allowedTypes = ($listOnly ?
[Type
::T_LIST
] : [Type
::T_LIST
, Type
::T_MAP
]);
1587 if ($this->matchChar('(')) {
1588 if ($this->enclosedExpression($lhs, $s, ")", $allowedTypes)) {
1590 $out = $this->expHelper($lhs, 0);
1595 $this->discardComments
= $discard;
1603 if (in_array(Type
::T_LIST
, $allowedTypes) && $this->matchChar('[')) {
1604 if ($this->enclosedExpression($lhs, $s, "]", [Type
::T_LIST
])) {
1606 $out = $this->expHelper($lhs, 0);
1610 $this->discardComments
= $discard;
1618 if (!$listOnly && $this->value($lhs)) {
1620 $out = $this->expHelper($lhs, 0);
1625 $this->discardComments
= $discard;
1630 $this->discardComments
= $discard;
1635 * Parse expression specifically checking for lists in parenthesis or brackets
1639 * @param string $closingParen
1640 * @param array $allowedTypes
1644 protected function enclosedExpression(&$out, $s, $closingParen = ")", $allowedTypes = [Type
::T_LIST
, Type
::T_MAP
])
1646 if ($this->matchChar($closingParen) && in_array(Type
::T_LIST
, $allowedTypes)) {
1647 $out = [Type
::T_LIST
, '', []];
1648 switch ($closingParen) {
1650 $out['enclosing'] = 'parent'; // parenthesis list
1653 $out['enclosing'] = 'bracket'; // bracketed list
1659 if ($this->valueList($out) && $this->matchChar($closingParen)
1660 && in_array($out[0], [Type
::T_LIST
, Type
::T_KEYWORD
])
1661 && in_array(Type
::T_LIST
, $allowedTypes)) {
1662 if ($out[0] !== Type
::T_LIST ||
! empty($out['enclosing'])) {
1663 $out = [Type
::T_LIST
, '', [$out]];
1665 switch ($closingParen) {
1667 $out['enclosing'] = 'parent'; // parenthesis list
1670 $out['enclosing'] = 'bracket'; // bracketed list
1678 if (in_array(Type
::T_MAP
, $allowedTypes) && $this->map($out)) {
1686 * Parse left-hand side of subexpression
1689 * @param integer $minP
1693 protected function expHelper($lhs, $minP)
1695 $operators = static::$operatorPattern;
1698 $whiteBefore = isset($this->buffer
[$this->count
- 1]) &&
1699 ctype_space($this->buffer
[$this->count
- 1]);
1701 while ($this->match($operators, $m, false) && static::$precedence[$m[1]] >= $minP) {
1702 $whiteAfter = isset($this->buffer
[$this->count
]) &&
1703 ctype_space($this->buffer
[$this->count
]);
1704 $varAfter = isset($this->buffer
[$this->count
]) &&
1705 $this->buffer
[$this->count
] === '$';
1707 $this->whitespace();
1711 // don't turn negative numbers into expressions
1712 if ($op === '-' && $whiteBefore && ! $whiteAfter && ! $varAfter) {
1716 if (! $this->value($rhs) && ! $this->expression($rhs, true, false)) {
1720 // peek and see if rhs belongs to next operator
1721 if ($this->peek($operators, $next) && static::$precedence[$next[1]] > static::$precedence[$op]) {
1722 $rhs = $this->expHelper($rhs, static::$precedence[$next[1]]);
1725 $lhs = [Type
::T_EXPRESSION
, $op, $lhs, $rhs, $this->inParens
, $whiteBefore, $whiteAfter];
1727 $whiteBefore = isset($this->buffer
[$this->count
- 1]) &&
1728 ctype_space($this->buffer
[$this->count
- 1]);
1743 protected function value(&$out)
1745 if (! isset($this->buffer
[$this->count
])) {
1750 $char = $this->buffer
[$this->count
];
1752 if ($this->literal('url(', 4) && $this->match('data:([a-z]+)\/([a-z0-9.+-]+);base64,', $m, false)) {
1755 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwyxz0123456789+/=',
1759 $this->count +
= $len;
1761 if ($this->matchChar(')')) {
1762 $content = substr($this->buffer
, $s, $this->count
- $s);
1763 $out = [Type
::T_KEYWORD
, $content];
1771 if ($this->literal('url(', 4, false) && $this->match('\s*(\/\/[^\s\)]+)\s*', $m)) {
1772 $content = 'url(' . $m[1];
1774 if ($this->matchChar(')')) {
1776 $out = [Type
::T_KEYWORD
, $content];
1785 if ($char === 'n' && $this->literal('not', 3, false)) {
1786 if ($this->whitespace() && $this->value($inner)) {
1787 $out = [Type
::T_UNARY
, 'not', $inner, $this->inParens
];
1794 if ($this->parenValue($inner)) {
1795 $out = [Type
::T_UNARY
, 'not', $inner, $this->inParens
];
1804 if ($char === '+') {
1807 if ($this->value($inner)) {
1808 $out = [Type
::T_UNARY
, '+', $inner, $this->inParens
];
1819 if ($char === '-') {
1822 if ($this->variable($inner) ||
$this->unit($inner) ||
$this->parenValue($inner)) {
1823 $out = [Type
::T_UNARY
, '-', $inner, $this->inParens
];
1832 if ($char === '(' && $this->parenValue($out)) {
1836 if ($char === '#') {
1837 if ($this->interpolation($out) ||
$this->color($out)) {
1842 if ($this->matchChar('&', true)) {
1843 $out = [Type
::T_SELF
];
1848 if ($char === '$' && $this->variable($out)) {
1852 if ($char === 'p' && $this->progid($out)) {
1856 if (($char === '"' ||
$char === "'") && $this->string($out)) {
1860 if ($this->unit($out)) {
1864 // unicode range with wildcards
1865 if ($this->literal('U+', 2) && $this->match('([0-9A-F]+\?*)(-([0-9A-F]+))?', $m, false)) {
1866 $out = [Type
::T_KEYWORD
, 'U+' . $m[0]];
1871 if ($this->keyword($keyword, false)) {
1872 if ($this->func($keyword, $out)) {
1876 $this->whitespace();
1878 if ($keyword === 'null') {
1879 $out = [Type
::T_NULL
];
1881 $out = [Type
::T_KEYWORD
, $keyword];
1891 * Parse parenthesized value
1897 protected function parenValue(&$out)
1901 $inParens = $this->inParens
;
1903 if ($this->matchChar('(')) {
1904 if ($this->matchChar(')')) {
1905 $out = [Type
::T_LIST
, '', []];
1910 $this->inParens
= true;
1912 if ($this->expression($exp) && $this->matchChar(')')) {
1914 $this->inParens
= $inParens;
1920 $this->inParens
= $inParens;
1933 protected function progid(&$out)
1937 if ($this->literal('progid:', 7, false) &&
1938 $this->openString('(', $fn) &&
1939 $this->matchChar('(')
1941 $this->openString(')', $args, '(');
1943 if ($this->matchChar(')')) {
1944 $out = [Type
::T_STRING
, '', [
1945 'progid:', $fn, '(', $args, ')'
1958 * Parse function call
1960 * @param string $name
1961 * @param array $func
1965 protected function func($name, &$func)
1969 if ($this->matchChar('(')) {
1970 if ($name === 'alpha' && $this->argumentList($args)) {
1971 $func = [Type
::T_FUNCTION
, $name, [Type
::T_STRING
, '', $args]];
1976 if ($name !== 'expression' && ! preg_match('/^(-[a-z]+-)?calc$/', $name)) {
1979 if ($this->argValues($args) && $this->matchChar(')')) {
1980 $func = [Type
::T_FUNCTION_CALL
, $name, $args];
1988 if (($this->openString(')', $str, '(') ||
true) &&
1989 $this->matchChar(')')
1993 if (! empty($str)) {
1994 $args[] = [null, [Type
::T_STRING
, '', [$str]]];
1997 $func = [Type
::T_FUNCTION_CALL
, $name, $args];
2009 * Parse function call argument list
2015 protected function argumentList(&$out)
2018 $this->matchChar('(');
2022 while ($this->keyword($var)) {
2023 if ($this->matchChar('=') && $this->expression($exp)) {
2024 $args[] = [Type
::T_STRING
, '', [$var . '=']];
2032 if (! $this->matchChar(',')) {
2036 $args[] = [Type
::T_STRING
, '', [', ']];
2039 if (! $this->matchChar(')') ||
! $args) {
2051 * Parse mixin/function definition argument list
2057 protected function argumentDef(&$out)
2060 $this->matchChar('(');
2064 while ($this->variable($var)) {
2065 $arg = [$var[1], null, false];
2069 if ($this->matchChar(':') && $this->genericList($defaultVal, 'expression')) {
2070 $arg[1] = $defaultVal;
2077 if ($this->literal('...', 3)) {
2078 $sss = $this->count
;
2080 if (! $this->matchChar(')')) {
2081 $this->throwParseError('... has to be after the final argument');
2092 if (! $this->matchChar(',')) {
2097 if (! $this->matchChar(')')) {
2115 protected function map(&$out)
2119 if (! $this->matchChar('(')) {
2126 while ($this->genericList($key, 'expression') && $this->matchChar(':') &&
2127 $this->genericList($value, 'expression')
2132 if (! $this->matchChar(',')) {
2137 if (! $keys ||
! $this->matchChar(')')) {
2143 $out = [Type
::T_MAP
, $keys, $values];
2155 protected function color(&$out)
2159 if ($this->match('(#([0-9a-f]+))', $m)) {
2160 if (in_array(strlen($m[2]), [3,4,6,8])) {
2161 $out = [Type
::T_KEYWORD
, $m[0]];
2173 * Parse number with unit
2175 * @param array $unit
2179 protected function unit(&$unit)
2183 if ($this->match('([0-9]*(\.)?[0-9]+)([%a-zA-Z]+)?', $m, false)) {
2184 if (strlen($this->buffer
) === $this->count ||
! ctype_digit($this->buffer
[$this->count
])) {
2185 $this->whitespace();
2187 $unit = new Node\
Number($m[1], empty($m[3]) ?
'' : $m[3]);
2205 protected function string(&$out)
2209 if ($this->matchChar('"', false)) {
2211 } elseif ($this->matchChar("'", false)) {
2218 $oldWhite = $this->eatWhiteDefault
;
2219 $this->eatWhiteDefault
= false;
2220 $hasInterpolation = false;
2222 while ($this->matchString($m, $delim)) {
2227 if ($m[2] === '#{') {
2228 $this->count
-= strlen($m[2]);
2230 if ($this->interpolation($inter, false)) {
2231 $content[] = $inter;
2232 $hasInterpolation = true;
2234 $this->count +
= strlen($m[2]);
2235 $content[] = '#{'; // ignore it
2237 } elseif ($m[2] === '\\') {
2238 if ($this->matchChar('"', false)) {
2239 $content[] = $m[2] . '"';
2240 } elseif ($this->matchChar("'", false)) {
2241 $content[] = $m[2] . "'";
2242 } elseif ($this->literal("\\", 1, false)) {
2243 $content[] = $m[2] . "\\";
2244 } elseif ($this->literal("\r\n", 2, false) ||
2245 $this->matchChar("\r", false) ||
2246 $this->matchChar("\n", false) ||
2247 $this->matchChar("\f", false)
2249 // this is a continuation escaping, to be ignored
2254 $this->count
-= strlen($delim);
2259 $this->eatWhiteDefault
= $oldWhite;
2261 if ($this->literal($delim, strlen($delim))) {
2262 if ($hasInterpolation) {
2265 foreach ($content as &$string) {
2266 if ($string === "\\\\") {
2268 } elseif ($string === "\\'") {
2270 } elseif ($string === '\\"') {
2276 $out = [Type
::T_STRING
, $delim, $content];
2287 * Parse keyword or interpolation
2290 * @param boolean $restricted
2294 protected function mixedKeyword(&$out, $restricted = false)
2298 $oldWhite = $this->eatWhiteDefault
;
2299 $this->eatWhiteDefault
= false;
2302 if ($restricted ?
$this->restrictedKeyword($key) : $this->keyword($key)) {
2307 if ($this->interpolation($inter)) {
2315 $this->eatWhiteDefault
= $oldWhite;
2321 if ($this->eatWhiteDefault
) {
2322 $this->whitespace();
2331 * Parse an unbounded string stopped by $end
2333 * @param string $end
2335 * @param string $nestingOpen
2339 protected function openString($end, &$out, $nestingOpen = null)
2341 $oldWhite = $this->eatWhiteDefault
;
2342 $this->eatWhiteDefault
= false;
2344 $patt = '(.*?)([\'"]|#\{|' . $this->pregQuote($end) . '|' . static::$commentPattern . ')';
2350 while ($this->match($patt, $m, false)) {
2351 if (isset($m[1]) && $m[1] !== '') {
2355 $nestingLevel +
= substr_count($m[1], $nestingOpen);
2361 $this->count
-= strlen($tok);
2363 if ($tok === $end && ! $nestingLevel--) {
2367 if (($tok === "'" ||
$tok === '"') && $this->string($str)) {
2372 if ($tok === '#{' && $this->interpolation($inter)) {
2373 $content[] = $inter;
2378 $this->count+
= strlen($tok);
2381 $this->eatWhiteDefault
= $oldWhite;
2388 if (is_string(end($content))) {
2389 $content[count($content) - 1] = rtrim(end($content));
2392 $out = [Type
::T_STRING
, '', $content];
2398 * Parser interpolation
2400 * @param string|array $out
2401 * @param boolean $lookWhite save information about whitespace before and after
2405 protected function interpolation(&$out, $lookWhite = true)
2407 $oldWhite = $this->eatWhiteDefault
;
2408 $this->eatWhiteDefault
= true;
2412 if ($this->literal('#{', 2) && $this->valueList($value) && $this->matchChar('}', false)) {
2413 if ($value === [Type
::T_SELF
]) {
2417 $left = ($s > 0 && preg_match('/\s/', $this->buffer
[$s - 1])) ?
' ' : '';
2418 $right = preg_match('/\s/', $this->buffer
[$this->count
]) ?
' ': '';
2420 $left = $right = false;
2423 $out = [Type
::T_INTERPOLATE
, $value, $left, $right];
2426 $this->eatWhiteDefault
= $oldWhite;
2428 if ($this->eatWhiteDefault
) {
2429 $this->whitespace();
2437 $this->eatWhiteDefault
= $oldWhite;
2443 * Parse property name (as an array of parts or a string)
2449 protected function propertyName(&$out)
2453 $oldWhite = $this->eatWhiteDefault
;
2454 $this->eatWhiteDefault
= false;
2457 if ($this->interpolation($inter)) {
2462 if ($this->keyword($text)) {
2467 if (! $parts && $this->match('[:.#]', $m, false)) {
2476 $this->eatWhiteDefault
= $oldWhite;
2482 // match comment hack
2484 static::$whitePattern,
2490 if (! empty($m[0])) {
2492 $this->count +
= strlen($m[0]);
2496 $this->whitespace(); // get any extra whitespace
2498 $out = [Type
::T_STRING
, '', $parts];
2504 * Parse comma separated selector list
2507 * @param boolean $subSelector
2511 protected function selectors(&$out, $subSelector = false)
2516 while ($this->selector($sel, $subSelector)) {
2517 $selectors[] = $sel;
2519 if (! $this->matchChar(',', true)) {
2523 while ($this->matchChar(',', true)) {
2540 * Parse whitespace separated selector list
2543 * @param boolean $subSelector
2547 protected function selector(&$out, $subSelector = false)
2554 if ($this->match('[>+~]+', $m, true)) {
2555 if ($subSelector && is_string($subSelector) && strpos($subSelector, 'nth-') === 0 &&
2556 $m[0] === '+' && $this->match("(\d+|n\b)", $counter)
2560 $selector[] = [$m[0]];
2565 if ($this->selectorSingle($part, $subSelector)) {
2566 $selector[] = $part;
2567 $this->match('\s+', $m);
2571 if ($this->match('\/[^\/]+\/', $m, true)) {
2572 $selector[] = [$m[0]];
2589 * Parse the parts that make up a selector
2592 * div[yes=no]#something.hello.world:nth-child(-2n+1)%placeholder
2596 * @param boolean $subSelector
2600 protected function selectorSingle(&$out, $subSelector = false)
2602 $oldWhite = $this->eatWhiteDefault
;
2603 $this->eatWhiteDefault
= false;
2607 if ($this->matchChar('*', false)) {
2612 if (! isset($this->buffer
[$this->count
])) {
2617 $char = $this->buffer
[$this->count
];
2619 // see if we can stop early
2620 if ($char === '{' ||
$char === ',' ||
$char === ';' ||
$char === '}' ||
$char === '@') {
2624 // parsing a sub selector in () stop with the closing )
2625 if ($subSelector && $char === ')') {
2632 $parts[] = Compiler
::$selfSelector;
2647 if ($char === '\\' && $this->match('\\\\\S', $m)) {
2652 if ($char === '%') {
2655 if ($this->placeholder($placeholder)) {
2657 $parts[] = $placeholder;
2664 if ($char === '#') {
2665 if ($this->interpolation($inter)) {
2675 // a pseudo selector
2676 if ($char === ':') {
2677 if ($this->buffer
[$this->count +
1] === ':') {
2685 if ($this->mixedKeyword($nameParts, true)) {
2688 foreach ($nameParts as $sub) {
2694 if ($nameParts === ['not'] ||
$nameParts === ['is'] ||
2695 $nameParts === ['has'] ||
$nameParts === ['where'] ||
2696 $nameParts === ['slotted'] ||
2697 $nameParts === ['nth-child'] ||
$nameParts == ['nth-last-child'] ||
2698 $nameParts === ['nth-of-type'] ||
$nameParts == ['nth-last-of-type']
2700 if ($this->matchChar('(', true) &&
2701 ($this->selectors($subs, reset($nameParts)) ||
true) &&
2702 $this->matchChar(')')
2706 while ($sub = array_shift($subs)) {
2707 while ($ps = array_shift($sub)) {
2708 foreach ($ps as &$p) {
2712 if (count($sub) && reset($sub)) {
2717 if (count($subs) && reset($subs)) {
2727 if ($this->matchChar('(') &&
2728 ($this->openString(')', $str, '(') ||
true) &&
2729 $this->matchChar(')')
2733 if (! empty($str)) {
2750 if ($subSelector && is_string($subSelector) && strpos($subSelector, 'nth-') === 0) {
2751 if ($this->match("(\s*(\+\s*|\-\s*)?(\d+|n|\d+n))+", $counter)) {
2752 $parts[] = $counter[0];
2753 //$parts[] = str_replace(' ', '', $counter[0]);
2760 // attribute selector
2761 if ($char === '[' &&
2762 $this->matchChar('[') &&
2763 ($this->openString(']', $str, '[') ||
true) &&
2764 $this->matchChar(']')
2768 if (! empty($str)) {
2779 if ($this->unit($unit)) {
2784 if ($this->restrictedKeyword($name)) {
2792 $this->eatWhiteDefault
= $oldWhite;
2810 protected function variable(&$out)
2814 if ($this->matchChar('$', false) && $this->keyword($name)) {
2815 $out = [Type
::T_VARIABLE
, $name];
2828 * @param string $word
2829 * @param boolean $eatWhitespace
2833 protected function keyword(&$word, $eatWhitespace = null)
2837 ?
'(([\pL\w\x{00A0}-\x{10FFFF}_\-\*!"\']|[\\\\].)([\pL\w\x{00A0}-\x{10FFFF}\-_"\']|[\\\\].)*)'
2838 : '(([\w_\-\*!"\']|[\\\\].)([\w\-_"\']|[\\\\].)*)',
2851 * Parse a keyword that should not start with a number
2853 * @param string $word
2854 * @param boolean $eatWhitespace
2858 protected function restrictedKeyword(&$word, $eatWhitespace = null)
2862 if ($this->keyword($word, $eatWhitespace) && (ord($word[0]) > 57 ||
ord($word[0]) < 48)) {
2872 * Parse a placeholder
2874 * @param string|array $placeholder
2878 protected function placeholder(&$placeholder)
2886 $placeholder = $m[1];
2891 if ($this->interpolation($placeholder)) {
2905 protected function url(&$out)
2907 if ($this->match('(url\(\s*(["\']?)([^)]+)\2\s*\))', $m)) {
2908 $out = [Type
::T_STRING
, '', ['url(' . $m[2] . $m[3] . $m[2] . ')']];
2917 * Consume an end of statement delimiter
2921 protected function end()
2923 if ($this->matchChar(';')) {
2927 if ($this->count
=== strlen($this->buffer
) ||
$this->buffer
[$this->count
] === '}') {
2928 // if there is end of file or a closing block next then we don't need a ;
2936 * Strip assignment flag from the list
2938 * @param array $value
2942 protected function stripAssignmentFlags(&$value)
2946 for ($token = &$value; $token[0] === Type
::T_LIST
&& ($s = count($token[2])); $token = &$lastNode) {
2947 $lastNode = &$token[2][$s - 1];
2949 while ($lastNode[0] === Type
::T_KEYWORD
&& in_array($lastNode[1], ['!default', '!global'])) {
2950 array_pop($token[2]);
2952 $node = end($token[2]);
2953 $token = $this->flattenList($token);
2954 $flags[] = $lastNode[1];
2963 * Strip optional flag from selector list
2965 * @param array $selectors
2969 protected function stripOptionalFlag(&$selectors)
2972 $selector = end($selectors);
2973 $part = end($selector);
2975 if ($part === ['!optional']) {
2976 array_pop($selectors[count($selectors) - 1]);
2985 * Turn list of length 1 into value type
2987 * @param array $value
2991 protected function flattenList($value)
2993 if ($value[0] === Type
::T_LIST
&& count($value[2]) === 1) {
2994 return $this->flattenList($value[2][0]);
3004 * advance counter to next occurrence of $what
3005 * $until - don't include $what in advance
3006 * $allowNewline, if string, will be used as valid char set
3009 protected function to($what, &$out, $until = false, $allowNewline = false)
3011 if (is_string($allowNewline)) {
3012 $validChars = $allowNewline;
3014 $validChars = $allowNewline ?
'.' : "[^\n]";
3019 if (! $this->match('(' . $validChars . '*?)' . $this->pregQuote($what), $m, ! $until)) {
3024 $this->count
-= strlen($what); // give back $what
3035 protected function show()
3037 if ($this->peek("(.*?)(\n|$)", $m, $this->count
)) {
3045 * Quote regular expression
3047 * @param string $what
3051 private function pregQuote($what)
3053 return preg_quote($what, '/');
3057 * Extract line numbers from buffer
3059 * @param string $buffer
3061 private function extractLineNumbers($buffer)
3063 $this->sourcePositions
= [0 => 0];
3066 while (($pos = strpos($buffer, "\n", $prev)) !== false) {
3067 $this->sourcePositions
[] = $pos;
3071 $this->sourcePositions
[] = strlen($buffer);
3073 if (substr($buffer, -1) !== "\n") {
3074 $this->sourcePositions
[] = strlen($buffer) +
1;
3079 * Get source line number and column (given character position in the buffer)
3081 * @param integer $pos
3085 private function getSourcePosition($pos)
3088 $high = count($this->sourcePositions
);
3090 while ($low < $high) {
3091 $mid = (int) (($high +
$low) / 2);
3093 if ($pos < $this->sourcePositions
[$mid]) {
3098 if ($pos >= $this->sourcePositions
[$mid +
1]) {
3103 return [$mid +
1, $pos - $this->sourcePositions
[$mid]];
3106 return [$low +
1, $pos - $this->sourcePositions
[$low]];
3110 * Save internal encoding
3112 private function saveEncoding()
3114 if (version_compare(PHP_VERSION
, '7.2.0') >= 0) {
3118 // deprecated in PHP 7.2
3119 $iniDirective = 'mbstring.func_overload';
3121 if (extension_loaded('mbstring') && ini_get($iniDirective) & 2) {
3122 $this->encoding
= mb_internal_encoding();
3124 mb_internal_encoding('iso-8859-1');
3129 * Restore internal encoding
3131 private function restoreEncoding()
3133 if (extension_loaded('mbstring') && $this->encoding
) {
3134 mb_internal_encoding($this->encoding
);