5 * @copyright 2012-2018 Leaf Corcoran
7 * @license http://opensource.org/licenses/MIT MIT
9 * @link http://leafo.github.io/scssphp
12 namespace Leafo\ScssPhp
;
14 use Leafo\ScssPhp\Base\Range
;
15 use Leafo\ScssPhp\Block
;
16 use Leafo\ScssPhp\Colors
;
17 use Leafo\ScssPhp\Compiler\Environment
;
18 use Leafo\ScssPhp\Exception\CompilerException
;
19 use Leafo\ScssPhp\Formatter\OutputBlock
;
20 use Leafo\ScssPhp\Node
;
21 use Leafo\ScssPhp\SourceMap\SourceMapGenerator
;
22 use Leafo\ScssPhp\Type
;
23 use Leafo\ScssPhp\Parser
;
24 use Leafo\ScssPhp\Util
;
27 * The scss compiler and parser.
29 * Converting SCSS to CSS is a three stage process. The incoming file is parsed
30 * by `Parser` into a syntax tree, then it is compiled into another tree
31 * representing the CSS structure by `Compiler`. The CSS tree is fed into a
32 * formatter, like `Formatter` which then outputs CSS as a string.
34 * During the first compile, all values are *reduced*, which means that their
35 * types are brought to the lowest form before being dump as strings. This
36 * handles math equations, variable dereferences, and the like.
38 * The `compile` function of `Compiler` is the entry point.
42 * The `Compiler` class creates an instance of the parser, feeds it SCSS code,
43 * then transforms the resulting tree to a CSS tree. This class also holds the
44 * evaluation context, such as all available mixins and variables at any given
47 * The `Parser` class is only concerned with parsing its input.
49 * The `Formatter` takes a CSS tree, and dumps it to a formatted string,
50 * handling things like indentation.
56 * @author Leaf Corcoran <leafot@gmail.com>
60 const LINE_COMMENTS
= 1;
65 const WITH_SUPPORTS
= 4;
68 const SOURCE_MAP_NONE
= 0;
69 const SOURCE_MAP_INLINE
= 1;
70 const SOURCE_MAP_FILE
= 2;
75 static protected $operatorNames = [
95 static protected $namespaces = [
101 static public $true = [Type
::T_KEYWORD
, 'true'];
102 static public $false = [Type
::T_KEYWORD
, 'false'];
103 static public $null = [Type
::T_NULL
];
104 static public $nullString = [Type
::T_STRING
, '', []];
105 static public $defaultValue = [Type
::T_KEYWORD
, ''];
106 static public $selfSelector = [Type
::T_SELF
];
107 static public $emptyList = [Type
::T_LIST
, '', []];
108 static public $emptyMap = [Type
::T_MAP
, [], []];
109 static public $emptyString = [Type
::T_STRING
, '"', []];
110 static public $with = [Type
::T_KEYWORD
, 'with'];
111 static public $without = [Type
::T_KEYWORD
, 'without'];
113 protected $importPaths = [''];
114 protected $importCache = [];
115 protected $importedFiles = [];
116 protected $userFunctions = [];
117 protected $registeredVars = [];
118 protected $registeredFeatures = [
119 'extend-selector-pseudoclass' => false,
121 'units-level-3' => false,
122 'global-variable-shadowing' => false,
125 protected $encoding = null;
126 protected $lineNumberStyle = null;
128 protected $sourceMap = self
::SOURCE_MAP_NONE
;
129 protected $sourceMapOptions = [];
132 * @var string|\Leafo\ScssPhp\Formatter
134 protected $formatter = 'Leafo\ScssPhp\Formatter\Nested';
137 protected $rootBlock;
140 * @var \Leafo\ScssPhp\Compiler\Environment
145 protected $charsetSeen;
146 protected $sourceNames;
148 private $indentLevel;
149 private $commentsSeen;
152 private $parsedFiles;
154 private $sourceIndex;
156 private $sourceColumn;
158 private $shouldEvaluate;
159 private $ignoreErrors;
164 public function __construct()
166 $this->parsedFiles
= [];
167 $this->sourceNames
= [];
175 * @param string $code
176 * @param string $path
180 public function compile($code, $path = null)
182 $this->indentLevel
= -1;
183 $this->commentsSeen
= [];
185 $this->extendsMap
= [];
186 $this->sourceIndex
= null;
187 $this->sourceLine
= null;
188 $this->sourceColumn
= null;
191 $this->storeEnv
= null;
192 $this->charsetSeen
= null;
193 $this->shouldEvaluate
= null;
194 $this->stderr
= fopen('php://stderr', 'w');
196 $this->parser
= $this->parserFactory($path);
197 $tree = $this->parser
->parse($code);
198 $this->parser
= null;
200 $this->formatter
= new $this->formatter();
201 $this->rootBlock
= null;
202 $this->rootEnv
= $this->pushEnv($tree);
204 $this->injectVariables($this->registeredVars
);
205 $this->compileRoot($tree);
208 $sourceMapGenerator = null;
210 if ($this->sourceMap
) {
211 if (is_object($this->sourceMap
) && $this->sourceMap
instanceof SourceMapGenerator
) {
212 $sourceMapGenerator = $this->sourceMap
;
213 $this->sourceMap
= self
::SOURCE_MAP_FILE
;
214 } elseif ($this->sourceMap
!== self
::SOURCE_MAP_NONE
) {
215 $sourceMapGenerator = new SourceMapGenerator($this->sourceMapOptions
);
219 $out = $this->formatter
->format($this->scope
, $sourceMapGenerator);
221 if (! empty($out) && $this->sourceMap
&& $this->sourceMap
!== self
::SOURCE_MAP_NONE
) {
222 $sourceMap = $sourceMapGenerator->generateJson();
223 $sourceMapUrl = null;
225 switch ($this->sourceMap
) {
226 case self
::SOURCE_MAP_INLINE
:
227 $sourceMapUrl = sprintf('data:application/json,%s', Util
::encodeURIComponent($sourceMap));
230 case self
::SOURCE_MAP_FILE
:
231 $sourceMapUrl = $sourceMapGenerator->saveMap($sourceMap);
235 $out .= sprintf('/*# sourceMappingURL=%s */', $sourceMapUrl);
244 * @param string $path
246 * @return \Leafo\ScssPhp\Parser
248 protected function parserFactory($path)
250 $parser = new Parser($path, count($this->sourceNames
), $this->encoding
);
252 $this->sourceNames
[] = $path;
253 $this->addParsedFile($path);
261 * @param array $target
262 * @param array $origin
266 protected function isSelfExtend($target, $origin)
268 foreach ($origin as $sel) {
269 if (in_array($target, $sel)) {
280 * @param array $target
281 * @param array $origin
282 * @param \stdClass $block
284 protected function pushExtends($target, $origin, $block)
286 if ($this->isSelfExtend($target, $origin)) {
290 $i = count($this->extends);
291 $this->extends[] = [$target, $origin, $block];
293 foreach ($target as $part) {
294 if (isset($this->extendsMap
[$part])) {
295 $this->extendsMap
[$part][] = $i;
297 $this->extendsMap
[$part] = [$i];
305 * @param string $type
306 * @param array $selectors
308 * @return \Leafo\ScssPhp\Formatter\OutputBlock
310 protected function makeOutputBlock($type, $selectors = null)
312 $out = new OutputBlock
;
316 $out->parent
= $this->scope
;
317 $out->selectors
= $selectors;
318 $out->depth
= $this->env
->depth
;
319 $out->sourceName
= $this->env
->block
->sourceName
;
320 $out->sourceLine
= $this->env
->block
->sourceLine
;
321 $out->sourceColumn
= $this->env
->block
->sourceColumn
;
329 * @param \Leafo\ScssPhp\Block $rootBlock
331 protected function compileRoot(Block
$rootBlock)
333 $this->rootBlock
= $this->scope
= $this->makeOutputBlock(Type
::T_ROOT
);
335 $this->compileChildrenNoReturn($rootBlock->children
, $this->scope
);
336 $this->flattenSelectors($this->scope
);
337 $this->missingSelectors();
341 * Report missing selectors
343 protected function missingSelectors()
345 foreach ($this->extends as $extend) {
346 if (isset($extend[3])) {
350 list($target, $origin, $block) = $extend;
352 // ignore if !optional
357 $target = implode(' ', $target);
358 $origin = $this->collapseSelectors($origin);
360 $this->sourceLine
= $block[Parser
::SOURCE_LINE
];
361 $this->throwError("\"$origin\" failed to @extend \"$target\". The selector \"$target\" was not found.");
368 * @param \Leafo\ScssPhp\Formatter\OutputBlock $block
369 * @param string $parentKey
371 protected function flattenSelectors(OutputBlock
$block, $parentKey = null)
373 if ($block->selectors
) {
376 foreach ($block->selectors
as $s) {
379 if (! is_array($s)) {
384 if (! empty($this->extendsMap
)) {
385 $this->matchExtends($s, $selectors);
388 array_walk($selectors, function (&$value) {
389 $value = serialize($value);
392 $selectors = array_unique($selectors);
394 array_walk($selectors, function (&$value) {
395 $value = unserialize($value);
400 $block->selectors
= [];
401 $placeholderSelector = false;
403 foreach ($selectors as $selector) {
404 if ($this->hasSelectorPlaceholder($selector)) {
405 $placeholderSelector = true;
409 $block->selectors
[] = $this->compileSelector($selector);
412 if ($placeholderSelector && 0 === count($block->selectors
) && null !== $parentKey) {
413 unset($block->parent
->children
[$parentKey]);
419 foreach ($block->children
as $key => $child) {
420 $this->flattenSelectors($child, $key);
427 * @param array $selector
429 * @param integer $from
430 * @param boolean $initial
432 protected function matchExtends($selector, &$out, $from = 0, $initial = true)
434 foreach ($selector as $i => $part) {
439 if ($this->matchExtendsSingle($part, $origin)) {
440 $after = array_slice($selector, $i +
1);
441 $before = array_slice($selector, 0, $i);
443 list($before, $nonBreakableBefore) = $this->extractRelationshipFromFragment($before);
445 foreach ($origin as $new) {
448 // remove shared parts
450 while ($k < $i && isset($new[$k]) && $selector[$k] === $new[$k]) {
456 $tempReplacement = $k > 0 ?
array_slice($new, $k) : $new;
458 for ($l = count($tempReplacement) - 1; $l >= 0; $l--) {
459 $slice = $tempReplacement[$l];
460 array_unshift($replacement, $slice);
462 if (! $this->isImmediateRelationshipCombinator(end($slice))) {
467 $afterBefore = $l != 0 ?
array_slice($tempReplacement, 0, $l) : [];
469 // Merge shared direct relationships.
470 $mergedBefore = $this->mergeDirectRelationships($afterBefore, $nonBreakableBefore);
472 $result = array_merge(
479 if ($result === $selector) {
485 // recursively check for more matches
486 $this->matchExtends($result, $out, count($before) +
count($mergedBefore), false);
488 // selector sequence merging
489 if (! empty($before) && count($new) > 1) {
490 $sharedParts = $k > 0 ?
array_slice($before, 0, $k) : [];
491 $postSharedParts = $k > 0 ?
array_slice($before, $k) : $before;
493 list($injectBetweenSharedParts, $nonBreakable2) = $this->extractRelationshipFromFragment($afterBefore);
495 $result2 = array_merge(
497 $injectBetweenSharedParts,
513 * Match extends single
515 * @param array $rawSingle
516 * @param array $outOrigin
520 protected function matchExtendsSingle($rawSingle, &$outOrigin)
525 foreach ($rawSingle as $part) {
527 if (! is_string($part)) {
531 if (! preg_match('/^[\[.:#%]/', $part) && count($single)) {
532 $single[count($single) - 1] .= $part;
538 $extendingDecoratedTag = false;
540 if (count($single) > 1) {
542 $extendingDecoratedTag = preg_match('/^[a-z0-9]+$/i', $single[0], $matches) ?
$matches[0] : false;
545 foreach ($single as $part) {
546 if (isset($this->extendsMap
[$part])) {
547 foreach ($this->extendsMap
[$part] as $idx) {
548 $counts[$idx] = isset($counts[$idx]) ?
$counts[$idx] +
1 : 1;
556 foreach ($counts as $idx => $count) {
557 list($target, $origin, /* $block */) = $this->extends[$idx];
560 if ($count !== count($target)) {
564 $this->extends[$idx][3] = true;
566 $rem = array_diff($single, $target);
568 foreach ($origin as $j => $new) {
569 // prevent infinite loop when target extends itself
570 if ($this->isSelfExtend($single, $origin)) {
574 $replacement = end($new);
576 // Extending a decorated tag with another tag is not possible.
577 if ($extendingDecoratedTag && $replacement[0] != $extendingDecoratedTag &&
578 preg_match('/^[a-z0-9]+$/i', $replacement[0])
584 $combined = $this->combineSelectorSingle($replacement, $rem);
586 if (count(array_diff($combined, $origin[$j][count($origin[$j]) - 1]))) {
587 $origin[$j][count($origin[$j]) - 1] = $combined;
591 $outOrigin = array_merge($outOrigin, $origin);
601 * Extract a relationship from the fragment.
603 * When extracting the last portion of a selector we will be left with a
604 * fragment which may end with a direction relationship combinator. This
605 * method will extract the relationship fragment and return it along side
608 * @param array $fragment The selector fragment maybe ending with a direction relationship combinator.
609 * @return array The selector without the relationship fragment if any, the relationship fragment.
611 protected function extractRelationshipFromFragment(array $fragment)
615 $j = $i = count($fragment);
618 $children = $j != $i ?
array_slice($fragment, $j, $i - $j) : [];
619 $parents = array_slice($fragment, 0, $j);
620 $slice = end($parents);
622 if (empty($slice) ||
! $this->isImmediateRelationshipCombinator($slice[0])) {
629 return [$parents, $children];
633 * Combine selector single
636 * @param array $other
640 protected function combineSelectorSingle($base, $other)
646 foreach ([$base, $other] as $single) {
647 foreach ($single as $part) {
648 if (preg_match('/^[\[.:#]/', $part)) {
651 } elseif (preg_match('/^[^_-]/', $part)) {
655 $tag[count($tag) - 1] .= $part;
657 $out[count($out) - 1] .= $part;
663 array_unshift($out, $tag[0]);
672 * @param \Leafo\ScssPhp\Block $media
674 protected function compileMedia(Block
$media)
676 $this->pushEnv($media);
678 $mediaQuery = $this->compileMediaQuery($this->multiplyMedia($this->env
));
680 if (! empty($mediaQuery)) {
681 $this->scope
= $this->makeOutputBlock(Type
::T_MEDIA
, [$mediaQuery]);
683 $parentScope = $this->mediaParent($this->scope
);
684 $parentScope->children
[] = $this->scope
;
686 // top level properties in a media cause it to be wrapped
689 foreach ($media->children
as $child) {
692 if ($type !== Type
::T_BLOCK
&&
693 $type !== Type
::T_MEDIA
&&
694 $type !== Type
::T_DIRECTIVE
&&
695 $type !== Type
::T_IMPORT
703 $wrapped = new Block
;
704 $wrapped->sourceName
= $media->sourceName
;
705 $wrapped->sourceIndex
= $media->sourceIndex
;
706 $wrapped->sourceLine
= $media->sourceLine
;
707 $wrapped->sourceColumn
= $media->sourceColumn
;
708 $wrapped->selectors
= [];
709 $wrapped->comments
= [];
710 $wrapped->parent
= $media;
711 $wrapped->children
= $media->children
;
713 $media->children
= [[Type
::T_BLOCK
, $wrapped]];
716 $this->compileChildrenNoReturn($media->children
, $this->scope
);
718 $this->scope
= $this->scope
->parent
;
727 * @param \Leafo\ScssPhp\Formatter\OutputBlock $scope
729 * @return \Leafo\ScssPhp\Formatter\OutputBlock
731 protected function mediaParent(OutputBlock
$scope)
733 while (! empty($scope->parent
)) {
734 if (! empty($scope->type
) && $scope->type
!== Type
::T_MEDIA
) {
738 $scope = $scope->parent
;
747 * @param \Leafo\ScssPhp\Block $block
749 protected function compileDirective(Block
$block)
751 $s = '@' . $block->name
;
753 if (! empty($block->value
)) {
754 $s .= ' ' . $this->compileValue($block->value
);
757 if ($block->name
=== 'keyframes' ||
substr($block->name
, -10) === '-keyframes') {
758 $this->compileKeyframeBlock($block, [$s]);
760 $this->compileNestedBlock($block, [$s]);
767 * @param \Leafo\ScssPhp\Block $block
769 protected function compileAtRoot(Block
$block)
771 $env = $this->pushEnv($block);
772 $envs = $this->compactEnv($env);
773 $without = isset($block->with
) ?
$this->compileWith($block->with
) : static::WITH_RULE
;
775 // wrap inline selector
776 if ($block->selector
) {
777 $wrapped = new Block
;
778 $wrapped->sourceName
= $block->sourceName
;
779 $wrapped->sourceIndex
= $block->sourceIndex
;
780 $wrapped->sourceLine
= $block->sourceLine
;
781 $wrapped->sourceColumn
= $block->sourceColumn
;
782 $wrapped->selectors
= $block->selector
;
783 $wrapped->comments
= [];
784 $wrapped->parent
= $block;
785 $wrapped->children
= $block->children
;
787 $block->children
= [[Type
::T_BLOCK
, $wrapped]];
790 $this->env
= $this->filterWithout($envs, $without);
791 $newBlock = $this->spliceTree($envs, $block, $without);
793 $saveScope = $this->scope
;
794 $this->scope
= $this->rootBlock
;
796 $this->compileChild($newBlock, $this->scope
);
798 $this->scope
= $saveScope;
799 $this->env
= $this->extractEnv($envs);
808 * @param \Leafo\ScssPhp\Block $block
809 * @param integer $without
813 private function spliceTree($envs, Block
$block, $without)
817 foreach ($envs as $e) {
818 if (! isset($e->block
)) {
822 if ($e->block
=== $block) {
826 if (isset($e->block
->type
) && $e->block
->type
=== Type
::T_AT_ROOT
) {
830 if ($e->block
&& $this->isWithout($without, $e->block
)) {
835 $b->sourceName
= $e->block
->sourceName
;
836 $b->sourceIndex
= $e->block
->sourceIndex
;
837 $b->sourceLine
= $e->block
->sourceLine
;
838 $b->sourceColumn
= $e->block
->sourceColumn
;
840 $b->comments
= $e->block
->comments
;
844 $type = isset($newBlock->type
) ?
$newBlock->type
: Type
::T_BLOCK
;
846 $b->children
= [[$type, $newBlock]];
848 $newBlock->parent
= $b;
849 } elseif (count($block->children
)) {
850 foreach ($block->children
as $child) {
851 if ($child[0] === Type
::T_BLOCK
) {
852 $child[1]->parent
= $b;
856 $b->children
= $block->children
;
859 if (isset($e->block
->type
)) {
860 $b->type
= $e->block
->type
;
863 if (isset($e->block
->name
)) {
864 $b->name
= $e->block
->name
;
867 if (isset($e->block
->queryList
)) {
868 $b->queryList
= $e->block
->queryList
;
871 if (isset($e->block
->value
)) {
872 $b->value
= $e->block
->value
;
878 $type = isset($newBlock->type
) ?
$newBlock->type
: Type
::T_BLOCK
;
880 return [$type, $newBlock];
884 * Compile @at-root's with: inclusion / without: exclusion into filter flags
890 private function compileWith($with)
893 'rule' => self
::WITH_RULE
,
894 'media' => self
::WITH_MEDIA
,
895 'supports' => self
::WITH_SUPPORTS
,
896 'all' => self
::WITH_ALL
,
899 // exclude selectors by default
900 $without = static::WITH_RULE
;
902 if ($this->libMapHasKey([$with, static::$with])) {
903 $without = static::WITH_ALL
;
905 $list = $this->coerceList($this->libMapGet([$with, static::$with]));
907 foreach ($list[2] as $item) {
908 $keyword = $this->compileStringContent($this->coerceString($item));
910 if (array_key_exists($keyword, $mapping)) {
911 $without &= ~
($mapping[$keyword]);
916 if ($this->libMapHasKey([$with, static::$without])) {
919 $list = $this->coerceList($this->libMapGet([$with, static::$without]));
921 foreach ($list[2] as $item) {
922 $keyword = $this->compileStringContent($this->coerceString($item));
924 if (array_key_exists($keyword, $mapping)) {
925 $without |
= $mapping[$keyword];
937 * @param integer $without
939 * @return \Leafo\ScssPhp\Compiler\Environment
941 private function filterWithout($envs, $without)
945 foreach ($envs as $e) {
946 if ($e->block
&& $this->isWithout($without, $e->block
)) {
953 return $this->extractEnv($filtered);
959 * @param integer $without
960 * @param \Leafo\ScssPhp\Block $block
964 private function isWithout($without, Block
$block)
966 if ((($without & static::WITH_RULE
) && isset($block->selectors
)) ||
967 (($without & static::WITH_MEDIA
) &&
968 isset($block->type
) && $block->type
=== Type
::T_MEDIA
) ||
969 (($without & static::WITH_SUPPORTS
) &&
970 isset($block->type
) && $block->type
=== Type
::T_DIRECTIVE
&&
971 isset($block->name
) && $block->name
=== 'supports')
980 * Compile keyframe block
982 * @param \Leafo\ScssPhp\Block $block
983 * @param array $selectors
985 protected function compileKeyframeBlock(Block
$block, $selectors)
987 $env = $this->pushEnv($block);
989 $envs = $this->compactEnv($env);
991 $this->env
= $this->extractEnv(array_filter($envs, function (Environment
$e) {
992 return ! isset($e->block
->selectors
);
995 $this->scope
= $this->makeOutputBlock($block->type
, $selectors);
996 $this->scope
->depth
= 1;
997 $this->scope
->parent
->children
[] = $this->scope
;
999 $this->compileChildrenNoReturn($block->children
, $this->scope
);
1001 $this->scope
= $this->scope
->parent
;
1002 $this->env
= $this->extractEnv($envs);
1008 * Compile nested block
1010 * @param \Leafo\ScssPhp\Block $block
1011 * @param array $selectors
1013 protected function compileNestedBlock(Block
$block, $selectors)
1015 $this->pushEnv($block);
1017 $this->scope
= $this->makeOutputBlock($block->type
, $selectors);
1018 $this->scope
->parent
->children
[] = $this->scope
;
1020 $this->compileChildrenNoReturn($block->children
, $this->scope
);
1022 $this->scope
= $this->scope
->parent
;
1028 * Recursively compiles a block.
1030 * A block is analogous to a CSS block in most cases. A single SCSS document
1031 * is encapsulated in a block when parsed, but it does not have parent tags
1032 * so all of its children appear on the root level when compiled.
1034 * Blocks are made up of selectors and children.
1036 * The children of a block are just all the blocks that are defined within.
1038 * Compiling the block involves pushing a fresh environment on the stack,
1039 * and iterating through the props, compiling each one.
1041 * @see Compiler::compileChild()
1043 * @param \Leafo\ScssPhp\Block $block
1045 protected function compileBlock(Block
$block)
1047 $env = $this->pushEnv($block);
1048 $env->selectors
= $this->evalSelectors($block->selectors
);
1050 $out = $this->makeOutputBlock(null);
1052 if (isset($this->lineNumberStyle
) && count($env->selectors
) && count($block->children
)) {
1053 $annotation = $this->makeOutputBlock(Type
::T_COMMENT
);
1054 $annotation->depth
= 0;
1056 $file = $this->sourceNames
[$block->sourceIndex
];
1057 $line = $block->sourceLine
;
1059 switch ($this->lineNumberStyle
) {
1060 case static::LINE_COMMENTS
:
1061 $annotation->lines
[] = '/* line ' . $line
1062 . ($file ?
', ' . $file : '')
1066 case static::DEBUG_INFO
:
1067 $annotation->lines
[] = '@media -sass-debug-info{'
1068 . ($file ?
'filename{font-family:"' . $file . '"}' : '')
1069 . 'line{font-family:' . $line . '}}';
1073 $this->scope
->children
[] = $annotation;
1076 $this->scope
->children
[] = $out;
1078 if (count($block->children
)) {
1079 $out->selectors
= $this->multiplySelectors($env);
1081 $this->compileChildrenNoReturn($block->children
, $out);
1084 $this->formatter
->stripSemicolon($out->lines
);
1090 * Compile root level comment
1092 * @param array $block
1094 protected function compileComment($block)
1096 $out = $this->makeOutputBlock(Type
::T_COMMENT
);
1097 $out->lines
[] = $block[1];
1098 $this->scope
->children
[] = $out;
1102 * Evaluate selectors
1104 * @param array $selectors
1108 protected function evalSelectors($selectors)
1110 $this->shouldEvaluate
= false;
1112 $selectors = array_map([$this, 'evalSelector'], $selectors);
1114 // after evaluating interpolates, we might need a second pass
1115 if ($this->shouldEvaluate
) {
1116 $buffer = $this->collapseSelectors($selectors);
1117 $parser = $this->parserFactory(__METHOD__
);
1119 if ($parser->parseSelector($buffer, $newSelectors)) {
1120 $selectors = array_map([$this, 'evalSelector'], $newSelectors);
1130 * @param array $selector
1134 protected function evalSelector($selector)
1136 return array_map([$this, 'evalSelectorPart'], $selector);
1140 * Evaluate selector part; replaces all the interpolates, stripping quotes
1142 * @param array $part
1146 protected function evalSelectorPart($part)
1148 foreach ($part as &$p) {
1149 if (is_array($p) && ($p[0] === Type
::T_INTERPOLATE ||
$p[0] === Type
::T_STRING
)) {
1150 $p = $this->compileValue($p);
1152 // force re-evaluation
1153 if (strpos($p, '&') !== false ||
strpos($p, ',') !== false) {
1154 $this->shouldEvaluate
= true;
1156 } elseif (is_string($p) && strlen($p) >= 2 &&
1157 ($first = $p[0]) && ($first === '"' ||
$first === "'") &&
1158 substr($p, -1) === $first
1160 $p = substr($p, 1, -1);
1164 return $this->flattenSelectorSingle($part);
1168 * Collapse selectors
1170 * @param array $selectors
1174 protected function collapseSelectors($selectors)
1178 foreach ($selectors as $selector) {
1181 array_walk_recursive(
1183 function ($value, $key) use (&$output) {
1191 return implode(', ', $parts);
1195 * Flatten selector single; joins together .classes and #ids
1197 * @param array $single
1201 protected function flattenSelectorSingle($single)
1205 foreach ($single as $part) {
1206 if (empty($joined) ||
1207 ! is_string($part) ||
1208 preg_match('/[\[.:#%]/', $part)
1214 if (is_array(end($joined))) {
1217 $joined[count($joined) - 1] .= $part;
1225 * Compile selector to string; self(&) should have been replaced by now
1227 * @param string|array $selector
1231 protected function compileSelector($selector)
1233 if (! is_array($selector)) {
1234 return $selector; // media and the like
1240 [$this, 'compileSelectorPart'],
1247 * Compile selector part
1249 * @param array $piece
1253 protected function compileSelectorPart($piece)
1255 foreach ($piece as &$p) {
1256 if (! is_array($p)) {
1266 $p = $this->compileValue($p);
1271 return implode($piece);
1275 * Has selector placeholder?
1277 * @param array $selector
1281 protected function hasSelectorPlaceholder($selector)
1283 if (! is_array($selector)) {
1287 foreach ($selector as $parts) {
1288 foreach ($parts as $part) {
1289 if (strlen($part) && '%' === $part[0]) {
1299 * Compile children and return result
1301 * @param array $stms
1302 * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
1306 protected function compileChildren($stms, OutputBlock
$out)
1308 foreach ($stms as $stm) {
1309 $ret = $this->compileChild($stm, $out);
1318 * Compile children and throw exception if unexpected @return
1320 * @param array $stms
1321 * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
1323 * @throws \Exception
1325 protected function compileChildrenNoReturn($stms, OutputBlock
$out)
1327 foreach ($stms as $stm) {
1328 $ret = $this->compileChild($stm, $out);
1331 $this->throwError('@return may only be used within a function');
1339 * Compile media query
1341 * @param array $queryList
1345 protected function compileMediaQuery($queryList)
1350 foreach ($queryList as $query) {
1354 foreach ($query as $q) {
1356 case Type
::T_MEDIA_TYPE
:
1358 $type = $this->mergeMediaTypes(
1360 array_map([$this, 'compileValue'], array_slice($q, 1))
1363 if (empty($type)) { // merge failed
1367 $type = array_map([$this, 'compileValue'], array_slice($q, 1));
1371 case Type
::T_MEDIA_EXPRESSION
:
1374 . $this->compileValue($q[1])
1375 . $this->formatter
->assignSeparator
1376 . $this->compileValue($q[2])
1380 . $this->compileValue($q[1])
1385 case Type
::T_MEDIA_VALUE
:
1386 $parts[] = $this->compileValue($q[1]);
1392 array_unshift($parts, implode(' ', array_filter($type)));
1395 if (! empty($parts)) {
1400 $out .= $this->formatter
->tagSeparator
;
1403 $out .= implode(' and ', $parts);
1410 protected function mergeDirectRelationships($selectors1, $selectors2)
1412 if (empty($selectors1) ||
empty($selectors2)) {
1413 return array_merge($selectors1, $selectors2);
1416 $part1 = end($selectors1);
1417 $part2 = end($selectors2);
1419 if (! $this->isImmediateRelationshipCombinator($part1[0]) ||
$part1 !== $part2) {
1420 return array_merge($selectors1, $selectors2);
1426 $part1 = array_pop($selectors1);
1427 $part2 = array_pop($selectors2);
1429 if ($this->isImmediateRelationshipCombinator($part1[0]) && $part1 !== $part2) {
1430 $merged = array_merge($selectors1, [$part1], $selectors2, [$part2], $merged);
1434 array_unshift($merged, $part1);
1435 array_unshift($merged, [array_pop($selectors1)[0] . array_pop($selectors2)[0]]);
1436 } while (! empty($selectors1) && ! empty($selectors2));
1444 * @param array $type1
1445 * @param array $type2
1447 * @return array|null
1449 protected function mergeMediaTypes($type1, $type2)
1451 if (empty($type1)) {
1455 if (empty($type2)) {
1462 if (count($type1) > 1) {
1463 $m1= strtolower($type1[0]);
1464 $t1= strtolower($type1[1]);
1466 $t1 = strtolower($type1[0]);
1472 if (count($type2) > 1) {
1473 $m2 = strtolower($type2[0]);
1474 $t2 = strtolower($type2[1]);
1476 $t2 = strtolower($type2[0]);
1479 if (($m1 === Type
::T_NOT
) ^
($m2 === Type
::T_NOT
)) {
1485 $m1 === Type
::T_NOT ?
$m2 : $m1,
1486 $m1 === Type
::T_NOT ?
$t2 : $t1,
1490 if ($m1 === Type
::T_NOT
&& $m2 === Type
::T_NOT
) {
1491 // CSS has no way of representing "neither screen nor print"
1496 return [Type
::T_NOT
, $t1];
1503 // t1 == t2, neither m1 nor m2 are "not"
1504 return [empty($m1)?
$m2 : $m1, $t1];
1508 * Compile import; returns true if the value was something that could be imported
1510 * @param array $rawPath
1512 * @param boolean $once
1516 protected function compileImport($rawPath, $out, $once = false)
1518 if ($rawPath[0] === Type
::T_STRING
) {
1519 $path = $this->compileStringContent($rawPath);
1521 if ($path = $this->findImport($path)) {
1522 if (! $once ||
! in_array($path, $this->importedFiles
)) {
1523 $this->importFile($path, $out);
1524 $this->importedFiles
[] = $path;
1533 if ($rawPath[0] === Type
::T_LIST
) {
1534 // handle a list of strings
1535 if (count($rawPath[2]) === 0) {
1539 foreach ($rawPath[2] as $path) {
1540 if ($path[0] !== Type
::T_STRING
) {
1545 foreach ($rawPath[2] as $path) {
1546 $this->compileImport($path, $out);
1556 * Compile child; returns a value to halt execution
1558 * @param array $child
1559 * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
1563 protected function compileChild($child, OutputBlock
$out)
1565 $this->sourceIndex
= isset($child[Parser
::SOURCE_INDEX
]) ?
$child[Parser
::SOURCE_INDEX
] : null;
1566 $this->sourceLine
= isset($child[Parser
::SOURCE_LINE
]) ?
$child[Parser
::SOURCE_LINE
] : -1;
1567 $this->sourceColumn
= isset($child[Parser
::SOURCE_COLUMN
]) ?
$child[Parser
::SOURCE_COLUMN
] : -1;
1569 switch ($child[0]) {
1570 case Type
::T_SCSSPHP_IMPORT_ONCE
:
1571 list(, $rawPath) = $child;
1573 $rawPath = $this->reduce($rawPath);
1575 if (! $this->compileImport($rawPath, $out, true)) {
1576 $out->lines
[] = '@import ' . $this->compileValue($rawPath) . ';';
1580 case Type
::T_IMPORT
:
1581 list(, $rawPath) = $child;
1583 $rawPath = $this->reduce($rawPath);
1585 if (! $this->compileImport($rawPath, $out)) {
1586 $out->lines
[] = '@import ' . $this->compileValue($rawPath) . ';';
1590 case Type
::T_DIRECTIVE
:
1591 $this->compileDirective($child[1]);
1594 case Type
::T_AT_ROOT
:
1595 $this->compileAtRoot($child[1]);
1599 $this->compileMedia($child[1]);
1603 $this->compileBlock($child[1]);
1606 case Type
::T_CHARSET
:
1607 if (! $this->charsetSeen
) {
1608 $this->charsetSeen
= true;
1610 $out->lines
[] = '@charset ' . $this->compileValue($child[1]) . ';';
1614 case Type
::T_ASSIGN
:
1615 list(, $name, $value) = $child;
1617 if ($name[0] === Type
::T_VARIABLE
) {
1618 $flags = isset($child[3]) ?
$child[3] : [];
1619 $isDefault = in_array('!default', $flags);
1620 $isGlobal = in_array('!global', $flags);
1623 $this->set($name[1], $this->reduce($value), false, $this->rootEnv
);
1627 $shouldSet = $isDefault &&
1628 (($result = $this->get($name[1], false)) === null
1629 ||
$result === static::$null);
1631 if (! $isDefault ||
$shouldSet) {
1632 $this->set($name[1], $this->reduce($value));
1637 $compiledName = $this->compileValue($name);
1639 // handle shorthand syntax: size / line-height
1640 if ($compiledName === 'font') {
1641 if ($value[0] === Type
::T_EXPRESSION
&& $value[1] === '/') {
1642 $value = $this->expToString($value);
1643 } elseif ($value[0] === Type
::T_LIST
) {
1644 foreach ($value[2] as &$item) {
1645 if ($item[0] === Type
::T_EXPRESSION
&& $item[1] === '/') {
1646 $item = $this->expToString($item);
1652 // if the value reduces to null from something else then
1653 // the property should be discarded
1654 if ($value[0] !== Type
::T_NULL
) {
1655 $value = $this->reduce($value);
1657 if ($value[0] === Type
::T_NULL ||
$value === static::$nullString) {
1662 $compiledValue = $this->compileValue($value);
1664 $out->lines
[] = $this->formatter
->property(
1670 case Type
::T_COMMENT
:
1671 if ($out->type
=== Type
::T_ROOT
) {
1672 $this->compileComment($child);
1676 $out->lines
[] = $child[1];
1680 case Type
::T_FUNCTION
:
1681 list(, $block) = $child;
1683 $this->set(static::$namespaces[$block->type
] . $block->name
, $block);
1686 case Type
::T_EXTEND
:
1687 list(, $selectors) = $child;
1689 foreach ($selectors as $sel) {
1690 $results = $this->evalSelectors([$sel]);
1692 foreach ($results as $result) {
1693 // only use the first one
1694 $result = current($result);
1696 $this->pushExtends($result, $out->selectors
, $child);
1702 list(, $if) = $child;
1704 if ($this->isTruthy($this->reduce($if->cond
, true))) {
1705 return $this->compileChildren($if->children
, $out);
1708 foreach ($if->cases
as $case) {
1709 if ($case->type
=== Type
::T_ELSE ||
1710 $case->type
=== Type
::T_ELSEIF
&& $this->isTruthy($this->reduce($case->cond
))
1712 return $this->compileChildren($case->children
, $out);
1718 list(, $each) = $child;
1720 $list = $this->coerceList($this->reduce($each->list));
1724 foreach ($list[2] as $item) {
1725 if (count($each->vars
) === 1) {
1726 $this->set($each->vars
[0], $item, true);
1728 list(,, $values) = $this->coerceList($item);
1730 foreach ($each->vars
as $i => $var) {
1731 $this->set($var, isset($values[$i]) ?
$values[$i] : static::$null, true);
1735 $ret = $this->compileChildren($each->children
, $out);
1738 if ($ret[0] !== Type
::T_CONTROL
) {
1754 list(, $while) = $child;
1756 while ($this->isTruthy($this->reduce($while->cond
, true))) {
1757 $ret = $this->compileChildren($while->children
, $out);
1760 if ($ret[0] !== Type
::T_CONTROL
) {
1772 list(, $for) = $child;
1774 $start = $this->reduce($for->start
, true);
1775 $end = $this->reduce($for->end
, true);
1777 if (! ($start[2] == $end[2] ||
$end->unitless())) {
1778 $this->throwError('Incompatible units: "%s" and "%s".', $start->unitStr(), $end->unitStr());
1787 $d = $start < $end ?
1 : -1;
1790 if ((! $for->until
&& $start - $d == $end) ||
1791 ($for->until
&& $start == $end)
1796 $this->set($for->var, new Node\
Number($start, $unit));
1799 $ret = $this->compileChildren($for->children
, $out);
1802 if ($ret[0] !== Type
::T_CONTROL
) {
1814 return [Type
::T_CONTROL
, true];
1816 case Type
::T_CONTINUE
:
1817 return [Type
::T_CONTROL
, false];
1819 case Type
::T_RETURN
:
1820 return $this->reduce($child[1], true);
1822 case Type
::T_NESTED_PROPERTY
:
1823 list(, $prop) = $child;
1826 $prefix = $this->compileValue($prop->prefix
) . '-';
1828 foreach ($prop->children
as $child) {
1829 switch ($child[0]) {
1830 case Type
::T_ASSIGN
:
1831 array_unshift($child[1][2], $prefix);
1834 case Type
::T_NESTED_PROPERTY
:
1835 array_unshift($child[1]->prefix
[2], $prefix);
1839 $prefixed[] = $child;
1842 $this->compileChildrenNoReturn($prefixed, $out);
1845 case Type
::T_INCLUDE
:
1846 // including a mixin
1847 list(, $name, $argValues, $content) = $child;
1849 $mixin = $this->get(static::$namespaces['mixin'] . $name, false);
1852 $this->throwError("Undefined mixin $name");
1856 $callingScope = $this->getStoreEnv();
1858 // push scope, apply args
1860 $this->env
->depth
--;
1862 $storeEnv = $this->storeEnv
;
1863 $this->storeEnv
= $this->env
;
1865 if (isset($content)) {
1866 $content->scope
= $callingScope;
1868 $this->setRaw(static::$namespaces['special'] . 'content', $content, $this->env
);
1871 if (isset($mixin->args
)) {
1872 $this->applyArguments($mixin->args
, $argValues);
1875 $this->env
->marker
= 'mixin';
1877 $this->compileChildrenNoReturn($mixin->children
, $out);
1879 $this->storeEnv
= $storeEnv;
1884 case Type
::T_MIXIN_CONTENT
:
1885 $content = $this->get(static::$namespaces['special'] . 'content', false, $this->getStoreEnv())
1886 ?
: $this->get(static::$namespaces['special'] . 'content', false, $this->env
);
1889 $content = new \
stdClass();
1890 $content->scope
= new \
stdClass();
1891 $content->children
= $this->storeEnv
->parent
->block
->children
;
1895 $storeEnv = $this->storeEnv
;
1896 $this->storeEnv
= $content->scope
;
1898 $this->compileChildrenNoReturn($content->children
, $out);
1900 $this->storeEnv
= $storeEnv;
1904 list(, $value) = $child;
1906 $line = $this->sourceLine
;
1907 $value = $this->compileValue($this->reduce($value, true));
1908 fwrite($this->stderr
, "Line $line DEBUG: $value\n");
1912 list(, $value) = $child;
1914 $line = $this->sourceLine
;
1915 $value = $this->compileValue($this->reduce($value, true));
1916 fwrite($this->stderr
, "Line $line WARN: $value\n");
1920 list(, $value) = $child;
1922 $line = $this->sourceLine
;
1923 $value = $this->compileValue($this->reduce($value, true));
1924 $this->throwError("Line $line ERROR: $value\n");
1927 case Type
::T_CONTROL
:
1928 $this->throwError('@break/@continue not permitted in this scope');
1932 $this->throwError("unknown child type: $child[0]");
1937 * Reduce expression to string
1943 protected function expToString($exp)
1945 list(, $op, $left, $right, /* $inParens */, $whiteLeft, $whiteRight) = $exp;
1947 $content = [$this->reduce($left)];
1959 $content[] = $this->reduce($right);
1961 return [Type
::T_STRING
, '', $content];
1967 * @param array $value
1971 protected function isTruthy($value)
1973 return $value !== static::$false && $value !== static::$null;
1977 * Is the value a direct relationship combinator?
1979 * @param string $value
1983 protected function isImmediateRelationshipCombinator($value)
1985 return $value === '>' ||
$value === '+' ||
$value === '~';
1989 * Should $value cause its operand to eval
1991 * @param array $value
1995 protected function shouldEval($value)
1997 switch ($value[0]) {
1998 case Type
::T_EXPRESSION
:
1999 if ($value[1] === '/') {
2000 return $this->shouldEval($value[2], $value[3]);
2004 case Type
::T_VARIABLE
:
2005 case Type
::T_FUNCTION_CALL
:
2015 * @param array $value
2016 * @param boolean $inExp
2018 * @return array|\Leafo\ScssPhp\Node\Number
2020 protected function reduce($value, $inExp = false)
2022 list($type) = $value;
2025 case Type
::T_EXPRESSION
:
2026 list(, $op, $left, $right, $inParens) = $value;
2028 $opName = isset(static::$operatorNames[$op]) ?
static::$operatorNames[$op] : $op;
2029 $inExp = $inExp ||
$this->shouldEval($left) ||
$this->shouldEval($right);
2031 $left = $this->reduce($left, true);
2033 if ($op !== 'and' && $op !== 'or') {
2034 $right = $this->reduce($right, true);
2037 // special case: looks like css shorthand
2038 if ($opName == 'div' && ! $inParens && ! $inExp && isset($right[2])
2039 && (($right[0] !== Type
::T_NUMBER
&& $right[2] != '')
2040 ||
($right[0] === Type
::T_NUMBER
&& ! $right->unitless()))
2042 return $this->expToString($value);
2045 $left = $this->coerceForExpression($left);
2046 $right = $this->coerceForExpression($right);
2051 $ucOpName = ucfirst($opName);
2052 $ucLType = ucfirst($ltype);
2053 $ucRType = ucfirst($rtype);
2056 // 1. op[op name][left type][right type]
2057 // 2. op[left type][right type] (passing the op as first arg
2059 $fn = "op${ucOpName}${ucLType}${ucRType}";
2061 if (is_callable([$this, $fn]) ||
2062 (($fn = "op${ucLType}${ucRType}") &&
2063 is_callable([$this, $fn]) &&
2065 (($fn = "op${ucOpName}") &&
2066 is_callable([$this, $fn]) &&
2069 $coerceUnit = false;
2071 if (! isset($genOp) &&
2072 $left[0] === Type
::T_NUMBER
&& $right[0] === Type
::T_NUMBER
2078 $targetUnit = $left[2];
2080 foreach ($right[2] as $unit => $exp) {
2081 $targetUnit[$unit] = (isset($targetUnit[$unit]) ?
$targetUnit[$unit] : 0) +
$exp;
2086 $targetUnit = $left[2];
2088 foreach ($right[2] as $unit => $exp) {
2089 $targetUnit[$unit] = (isset($targetUnit[$unit]) ?
$targetUnit[$unit] : 0) - $exp;
2094 $targetUnit = $left[2];
2098 $targetUnit = $left->unitless() ?
$right[2] : $left[2];
2101 if (! $left->unitless() && ! $right->unitless()) {
2102 $left = $left->normalize();
2103 $right = $right->normalize();
2107 $shouldEval = $inParens ||
$inExp;
2109 if (isset($passOp)) {
2110 $out = $this->$fn($op, $left, $right, $shouldEval);
2112 $out = $this->$fn($left, $right, $shouldEval);
2116 if ($coerceUnit && $out[0] === Type
::T_NUMBER
) {
2117 $out = $out->coerce($targetUnit);
2124 return $this->expToString($value);
2127 list(, $op, $exp, $inParens) = $value;
2129 $inExp = $inExp ||
$this->shouldEval($exp);
2130 $exp = $this->reduce($exp);
2132 if ($exp[0] === Type
::T_NUMBER
) {
2135 return new Node\
Number($exp[1], $exp[2]);
2138 return new Node\
Number(-$exp[1], $exp[2]);
2142 if ($op === 'not') {
2143 if ($inExp ||
$inParens) {
2144 if ($exp === static::$false ||
$exp === static::$null) {
2145 return static::$true;
2148 return static::$false;
2154 return [Type
::T_STRING
, '', [$op, $exp]];
2156 case Type
::T_VARIABLE
:
2157 list(, $name) = $value;
2159 return $this->reduce($this->get($name));
2162 foreach ($value[2] as &$item) {
2163 $item = $this->reduce($item);
2169 foreach ($value[1] as &$item) {
2170 $item = $this->reduce($item);
2173 foreach ($value[2] as &$item) {
2174 $item = $this->reduce($item);
2179 case Type
::T_STRING
:
2180 foreach ($value[2] as &$item) {
2181 if (is_array($item) ||
$item instanceof \ArrayAccess
) {
2182 $item = $this->reduce($item);
2188 case Type
::T_INTERPOLATE
:
2189 $value[1] = $this->reduce($value[1]);
2193 case Type
::T_FUNCTION_CALL
:
2194 list(, $name, $argValues) = $value;
2196 return $this->fncall($name, $argValues);
2206 * @param string $name
2207 * @param array $argValues
2209 * @return array|null
2211 private function fncall($name, $argValues)
2214 if ($this->callScssFunction($name, $argValues, $returnValue)) {
2215 return $returnValue;
2218 // native PHP functions
2219 if ($this->callNativeFunction($name, $argValues, $returnValue)) {
2220 return $returnValue;
2223 // for CSS functions, simply flatten the arguments into a list
2226 foreach ((array) $argValues as $arg) {
2227 if (empty($arg[0])) {
2228 $listArgs[] = $this->reduce($arg[1]);
2232 return [Type
::T_FUNCTION
, $name, [Type
::T_LIST
, ',', $listArgs]];
2238 * @param string $name
2242 protected function normalizeName($name)
2244 return str_replace('-', '_', $name);
2250 * @param array $value
2254 public function normalizeValue($value)
2256 $value = $this->coerceForExpression($this->reduce($value));
2257 list($type) = $value;
2261 $value = $this->extractInterpolation($value);
2263 if ($value[0] !== Type
::T_LIST
) {
2264 return [Type
::T_KEYWORD
, $this->compileValue($value)];
2267 foreach ($value[2] as $key => $item) {
2268 $value[2][$key] = $this->normalizeValue($item);
2273 case Type
::T_STRING
:
2274 return [$type, '"', [$this->compileStringContent($value)]];
2276 case Type
::T_NUMBER
:
2277 return $value->normalize();
2279 case Type
::T_INTERPOLATE
:
2280 return [Type
::T_KEYWORD
, $this->compileValue($value)];
2290 * @param array $left
2291 * @param array $right
2293 * @return \Leafo\ScssPhp\Node\Number
2295 protected function opAddNumberNumber($left, $right)
2297 return new Node\
Number($left[1] +
$right[1], $left[2]);
2303 * @param array $left
2304 * @param array $right
2306 * @return \Leafo\ScssPhp\Node\Number
2308 protected function opMulNumberNumber($left, $right)
2310 return new Node\
Number($left[1] * $right[1], $left[2]);
2316 * @param array $left
2317 * @param array $right
2319 * @return \Leafo\ScssPhp\Node\Number
2321 protected function opSubNumberNumber($left, $right)
2323 return new Node\
Number($left[1] - $right[1], $left[2]);
2329 * @param array $left
2330 * @param array $right
2332 * @return array|\Leafo\ScssPhp\Node\Number
2334 protected function opDivNumberNumber($left, $right)
2336 if ($right[1] == 0) {
2337 return [Type
::T_STRING
, '', [$left[1] . $left[2] . '/' . $right[1] . $right[2]]];
2340 return new Node\
Number($left[1] / $right[1], $left[2]);
2346 * @param array $left
2347 * @param array $right
2349 * @return \Leafo\ScssPhp\Node\Number
2351 protected function opModNumberNumber($left, $right)
2353 return new Node\
Number($left[1] %
$right[1], $left[2]);
2359 * @param array $left
2360 * @param array $right
2364 protected function opAdd($left, $right)
2366 if ($strLeft = $this->coerceString($left)) {
2367 if ($right[0] === Type
::T_STRING
) {
2371 $strLeft[2][] = $right;
2376 if ($strRight = $this->coerceString($right)) {
2377 if ($left[0] === Type
::T_STRING
) {
2381 array_unshift($strRight[2], $left);
2390 * @param array $left
2391 * @param array $right
2392 * @param boolean $shouldEval
2396 protected function opAnd($left, $right, $shouldEval)
2398 if (! $shouldEval) {
2402 if ($left !== static::$false and $left !== static::$null) {
2403 return $this->reduce($right, true);
2412 * @param array $left
2413 * @param array $right
2414 * @param boolean $shouldEval
2418 protected function opOr($left, $right, $shouldEval)
2420 if (! $shouldEval) {
2424 if ($left !== static::$false and $left !== static::$null) {
2428 return $this->reduce($right, true);
2435 * @param array $left
2436 * @param array $right
2440 protected function opColorColor($op, $left, $right)
2442 $out = [Type
::T_COLOR
];
2444 foreach ([1, 2, 3] as $i) {
2445 $lval = isset($left[$i]) ?
$left[$i] : 0;
2446 $rval = isset($right[$i]) ?
$right[$i] : 0;
2450 $out[] = $lval +
$rval;
2454 $out[] = $lval - $rval;
2458 $out[] = $lval * $rval;
2462 $out[] = $lval %
$rval;
2467 $this->throwError("color: Can't divide by zero");
2471 $out[] = (int) ($lval / $rval);
2475 return $this->opEq($left, $right);
2478 return $this->opNeq($left, $right);
2481 $this->throwError("color: unknown op $op");
2486 if (isset($left[4])) {
2488 } elseif (isset($right[4])) {
2489 $out[4] = $right[4];
2492 return $this->fixColor($out);
2496 * Compare color and number
2499 * @param array $left
2500 * @param array $right
2504 protected function opColorNumber($op, $left, $right)
2508 return $this->opColorColor(
2511 [Type
::T_COLOR
, $value, $value, $value]
2516 * Compare number and color
2519 * @param array $left
2520 * @param array $right
2524 protected function opNumberColor($op, $left, $right)
2528 return $this->opColorColor(
2530 [Type
::T_COLOR
, $value, $value, $value],
2536 * Compare number1 == number2
2538 * @param array $left
2539 * @param array $right
2543 protected function opEq($left, $right)
2545 if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
2549 $left = $this->compileValue($lStr);
2550 $right = $this->compileValue($rStr);
2553 return $this->toBool($left === $right);
2557 * Compare number1 != number2
2559 * @param array $left
2560 * @param array $right
2564 protected function opNeq($left, $right)
2566 if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
2570 $left = $this->compileValue($lStr);
2571 $right = $this->compileValue($rStr);
2574 return $this->toBool($left !== $right);
2578 * Compare number1 >= number2
2580 * @param array $left
2581 * @param array $right
2585 protected function opGteNumberNumber($left, $right)
2587 return $this->toBool($left[1] >= $right[1]);
2591 * Compare number1 > number2
2593 * @param array $left
2594 * @param array $right
2598 protected function opGtNumberNumber($left, $right)
2600 return $this->toBool($left[1] > $right[1]);
2604 * Compare number1 <= number2
2606 * @param array $left
2607 * @param array $right
2611 protected function opLteNumberNumber($left, $right)
2613 return $this->toBool($left[1] <= $right[1]);
2617 * Compare number1 < number2
2619 * @param array $left
2620 * @param array $right
2624 protected function opLtNumberNumber($left, $right)
2626 return $this->toBool($left[1] < $right[1]);
2630 * Three-way comparison, aka spaceship operator
2632 * @param array $left
2633 * @param array $right
2635 * @return \Leafo\ScssPhp\Node\Number
2637 protected function opCmpNumberNumber($left, $right)
2639 $n = $left[1] - $right[1];
2641 return new Node\
Number($n ?
$n / abs($n) : 0, '');
2649 * @param mixed $thing
2653 public function toBool($thing)
2655 return $thing ?
static::$true : static::$false;
2659 * Compiles a primitive value into a CSS property value.
2661 * Values in scssphp are typed by being wrapped in arrays, their format is
2664 * array(type, contents [, additional_contents]*)
2666 * The input is expected to be reduced. This function will not work on
2667 * things like expressions and variables.
2671 * @param array $value
2675 public function compileValue($value)
2677 $value = $this->reduce($value);
2679 list($type) = $value;
2682 case Type
::T_KEYWORD
:
2686 // [1] - red component (either number for a %)
2687 // [2] - green component
2688 // [3] - blue component
2689 // [4] - optional alpha component
2690 list(, $r, $g, $b) = $value;
2696 if (count($value) === 5 && $value[4] !== 1) { // rgba
2697 return 'rgba(' . $r . ', ' . $g . ', ' . $b . ', ' . $value[4] . ')';
2700 $h = sprintf('#%02x%02x%02x', $r, $g, $b);
2702 // Converting hex color to short notation (e.g. #003399 to #039)
2703 if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
2704 $h = '#' . $h[1] . $h[3] . $h[5];
2709 case Type
::T_NUMBER
:
2710 return $value->output($this);
2712 case Type
::T_STRING
:
2713 return $value[1] . $this->compileStringContent($value) . $value[1];
2715 case Type
::T_FUNCTION
:
2716 $args = ! empty($value[2]) ?
$this->compileValue($value[2]) : '';
2718 return "$value[1]($args)";
2721 $value = $this->extractInterpolation($value);
2723 if ($value[0] !== Type
::T_LIST
) {
2724 return $this->compileValue($value);
2727 list(, $delim, $items) = $value;
2729 if ($delim !== ' ') {
2735 foreach ($items as $item) {
2736 if ($item[0] === Type
::T_NULL
) {
2740 $filtered[] = $this->compileValue($item);
2743 return implode("$delim", $filtered);
2747 $values = $value[2];
2750 for ($i = 0, $s = count($keys); $i < $s; $i++
) {
2751 $filtered[$this->compileValue($keys[$i])] = $this->compileValue($values[$i]);
2754 array_walk($filtered, function (&$value, $key) {
2755 $value = $key . ': ' . $value;
2758 return '(' . implode(', ', $filtered) . ')';
2760 case Type
::T_INTERPOLATED
:
2761 // node created by extractInterpolation
2762 list(, $interpolate, $left, $right) = $value;
2763 list(,, $whiteLeft, $whiteRight) = $interpolate;
2765 $left = count($left[2]) > 0 ?
2766 $this->compileValue($left) . $whiteLeft : '';
2768 $right = count($right[2]) > 0 ?
2769 $whiteRight . $this->compileValue($right) : '';
2771 return $left . $this->compileValue($interpolate) . $right;
2773 case Type
::T_INTERPOLATE
:
2775 list(, $exp) = $value;
2777 // strip quotes if it's a string
2778 $reduced = $this->reduce($exp);
2780 switch ($reduced[0]) {
2782 $reduced = $this->extractInterpolation($reduced);
2784 if ($reduced[0] !== Type
::T_LIST
) {
2788 list(, $delim, $items) = $reduced;
2790 if ($delim !== ' ') {
2796 foreach ($items as $item) {
2797 if ($item[0] === Type
::T_NULL
) {
2801 $temp = $this->compileValue([Type
::T_KEYWORD
, $item]);
2802 if ($temp[0] === Type
::T_STRING
) {
2803 $filtered[] = $this->compileStringContent($temp);
2804 } elseif ($temp[0] === Type
::T_KEYWORD
) {
2805 $filtered[] = $temp[1];
2807 $filtered[] = $this->compileValue($temp);
2811 $reduced = [Type
::T_KEYWORD
, implode("$delim", $filtered)];
2814 case Type
::T_STRING
:
2815 $reduced = [Type
::T_KEYWORD
, $this->compileStringContent($reduced)];
2819 $reduced = [Type
::T_KEYWORD
, ''];
2822 return $this->compileValue($reduced);
2828 $this->throwError("unknown value type: $type");
2835 * @param array $list
2839 protected function flattenList($list)
2841 return $this->compileValue($list);
2845 * Compile string content
2847 * @param array $string
2851 protected function compileStringContent($string)
2855 foreach ($string[2] as $part) {
2856 if (is_array($part) ||
$part instanceof \ArrayAccess
) {
2857 $parts[] = $this->compileValue($part);
2863 return implode($parts);
2867 * Extract interpolation; it doesn't need to be recursive, compileValue will handle that
2869 * @param array $list
2873 protected function extractInterpolation($list)
2877 foreach ($items as $i => $item) {
2878 if ($item[0] === Type
::T_INTERPOLATE
) {
2879 $before = [Type
::T_LIST
, $list[1], array_slice($items, 0, $i)];
2880 $after = [Type
::T_LIST
, $list[1], array_slice($items, $i +
1)];
2882 return [Type
::T_INTERPOLATED
, $item, $before, $after];
2890 * Find the final set of selectors
2892 * @param \Leafo\ScssPhp\Compiler\Environment $env
2896 protected function multiplySelectors(Environment
$env)
2898 $envs = $this->compactEnv($env);
2900 $parentSelectors = [[]];
2902 while ($env = array_pop($envs)) {
2903 if (empty($env->selectors
)) {
2909 foreach ($env->selectors
as $selector) {
2910 foreach ($parentSelectors as $parent) {
2911 $selectors[] = $this->joinSelectors($parent, $selector);
2915 $parentSelectors = $selectors;
2922 * Join selectors; looks for & to replace, or append parent before child
2924 * @param array $parent
2925 * @param array $child
2929 protected function joinSelectors($parent, $child)
2934 foreach ($child as $part) {
2937 foreach ($part as $p) {
2938 if ($p === static::$selfSelector) {
2941 foreach ($parent as $i => $parentPart) {
2947 foreach ($parentPart as $pp) {
2959 return $setSelf ?
$out : array_merge($parent, $child);
2965 * @param \Leafo\ScssPhp\Compiler\Environment $env
2966 * @param array $childQueries
2970 protected function multiplyMedia(Environment
$env = null, $childQueries = null)
2972 if (! isset($env) ||
2973 ! empty($env->block
->type
) && $env->block
->type
!== Type
::T_MEDIA
2975 return $childQueries;
2978 // plain old block, skip
2979 if (empty($env->block
->type
)) {
2980 return $this->multiplyMedia($env->parent
, $childQueries);
2983 $parentQueries = isset($env->block
->queryList
)
2984 ?
$env->block
->queryList
2985 : [[[Type
::T_MEDIA_VALUE
, $env->block
->value
]]];
2987 if ($childQueries === null) {
2988 $childQueries = $parentQueries;
2990 $originalQueries = $childQueries;
2993 foreach ($parentQueries as $parentQuery) {
2994 foreach ($originalQueries as $childQuery) {
2995 $childQueries []= array_merge($parentQuery, $childQuery);
3000 return $this->multiplyMedia($env->parent
, $childQueries);
3004 * Convert env linked list to stack
3006 * @param \Leafo\ScssPhp\Compiler\Environment $env
3010 private function compactEnv(Environment
$env)
3012 for ($envs = []; $env; $env = $env->parent
) {
3020 * Convert env stack to singly linked list
3022 * @param array $envs
3024 * @return \Leafo\ScssPhp\Compiler\Environment
3026 private function extractEnv($envs)
3028 for ($env = null; $e = array_pop($envs);) {
3039 * @param \Leafo\ScssPhp\Block $block
3041 * @return \Leafo\ScssPhp\Compiler\Environment
3043 protected function pushEnv(Block
$block = null)
3045 $env = new Environment
;
3046 $env->parent
= $this->env
;
3048 $env->block
= $block;
3049 $env->depth
= isset($this->env
->depth
) ?
$this->env
->depth +
1 : 0;
3059 protected function popEnv()
3061 $this->env
= $this->env
->parent
;
3065 * Get store environment
3067 * @return \Leafo\ScssPhp\Compiler\Environment
3069 protected function getStoreEnv()
3071 return isset($this->storeEnv
) ?
$this->storeEnv
: $this->env
;
3077 * @param string $name
3078 * @param mixed $value
3079 * @param boolean $shadow
3080 * @param \Leafo\ScssPhp\Compiler\Environment $env
3082 protected function set($name, $value, $shadow = false, Environment
$env = null)
3084 $name = $this->normalizeName($name);
3086 if (! isset($env)) {
3087 $env = $this->getStoreEnv();
3091 $this->setRaw($name, $value, $env);
3093 $this->setExisting($name, $value, $env);
3098 * Set existing variable
3100 * @param string $name
3101 * @param mixed $value
3102 * @param \Leafo\ScssPhp\Compiler\Environment $env
3104 protected function setExisting($name, $value, Environment
$env)
3108 $hasNamespace = $name[0] === '^' ||
$name[0] === '@' ||
$name[0] === '%';
3111 if (array_key_exists($name, $env->store
)) {
3115 if (! $hasNamespace && isset($env->marker
)) {
3120 if (! isset($env->parent
)) {
3125 $env = $env->parent
;
3128 $env->store
[$name] = $value;
3134 * @param string $name
3135 * @param mixed $value
3136 * @param \Leafo\ScssPhp\Compiler\Environment $env
3138 protected function setRaw($name, $value, Environment
$env)
3140 $env->store
[$name] = $value;
3148 * @param string $name
3149 * @param boolean $shouldThrow
3150 * @param \Leafo\ScssPhp\Compiler\Environment $env
3154 public function get($name, $shouldThrow = true, Environment
$env = null)
3156 $normalizedName = $this->normalizeName($name);
3157 $specialContentKey = static::$namespaces['special'] . 'content';
3159 if (! isset($env)) {
3160 $env = $this->getStoreEnv();
3163 $nextIsRoot = false;
3164 $hasNamespace = $normalizedName[0] === '^' ||
$normalizedName[0] === '@' ||
$normalizedName[0] === '%';
3167 if (array_key_exists($normalizedName, $env->store
)) {
3168 return $env->store
[$normalizedName];
3171 if (! $hasNamespace && isset($env->marker
)) {
3172 if (! $nextIsRoot && ! empty($env->store
[$specialContentKey])) {
3173 $env = $env->store
[$specialContentKey]->scope
;
3178 $env = $this->rootEnv
;
3182 if (! isset($env->parent
)) {
3186 $env = $env->parent
;
3190 $this->throwError("Undefined variable \$$name");
3199 * @param string $name
3200 * @param \Leafo\ScssPhp\Compiler\Environment $env
3204 protected function has($name, Environment
$env = null)
3206 return $this->get($name, false, $env) !== null;
3212 * @param array $args
3214 protected function injectVariables(array $args)
3220 $parser = $this->parserFactory(__METHOD__
);
3222 foreach ($args as $name => $strValue) {
3223 if ($name[0] === '$') {
3224 $name = substr($name, 1);
3227 if (! $parser->parseValue($strValue, $value)) {
3228 $value = $this->coerceValue($strValue);
3231 $this->set($name, $value);
3240 * @param array $variables
3242 public function setVariables(array $variables)
3244 $this->registeredVars
= array_merge($this->registeredVars
, $variables);
3252 * @param string $name
3254 public function unsetVariable($name)
3256 unset($this->registeredVars
[$name]);
3260 * Returns list of variables
3266 public function getVariables()
3268 return $this->registeredVars
;
3272 * Adds to list of parsed files
3276 * @param string $path
3278 public function addParsedFile($path)
3280 if (isset($path) && file_exists($path)) {
3281 $this->parsedFiles
[realpath($path)] = filemtime($path);
3286 * Returns list of parsed files
3292 public function getParsedFiles()
3294 return $this->parsedFiles
;
3302 * @param string $path
3304 public function addImportPath($path)
3306 if (! in_array($path, $this->importPaths
)) {
3307 $this->importPaths
[] = $path;
3316 * @param string|array $path
3318 public function setImportPaths($path)
3320 $this->importPaths
= (array) $path;
3324 * Set number precision
3328 * @param integer $numberPrecision
3330 public function setNumberPrecision($numberPrecision)
3332 Node\Number
::$precision = $numberPrecision;
3340 * @param string $formatterName
3342 public function setFormatter($formatterName)
3344 $this->formatter
= $formatterName;
3348 * Set line number style
3352 * @param string $lineNumberStyle
3354 public function setLineNumberStyle($lineNumberStyle)
3356 $this->lineNumberStyle
= $lineNumberStyle;
3360 * Enable/disable source maps
3364 * @param integer $sourceMap
3366 public function setSourceMap($sourceMap)
3368 $this->sourceMap
= $sourceMap;
3372 * Set source map options
3376 * @param array $sourceMapOptions
3378 public function setSourceMapOptions($sourceMapOptions)
3380 $this->sourceMapOptions
= $sourceMapOptions;
3388 * @param string $name
3389 * @param callable $func
3390 * @param array $prototype
3392 public function registerFunction($name, $func, $prototype = null)
3394 $this->userFunctions
[$this->normalizeName($name)] = [$func, $prototype];
3398 * Unregister function
3402 * @param string $name
3404 public function unregisterFunction($name)
3406 unset($this->userFunctions
[$this->normalizeName($name)]);
3414 * @param string $name
3416 public function addFeature($name)
3418 $this->registeredFeatures
[$name] = true;
3424 * @param string $path
3427 protected function importFile($path, $out)
3429 // see if tree is cached
3430 $realPath = realpath($path);
3432 if (isset($this->importCache
[$realPath])) {
3433 $this->handleImportLoop($realPath);
3435 $tree = $this->importCache
[$realPath];
3437 $code = file_get_contents($path);
3438 $parser = $this->parserFactory($path);
3439 $tree = $parser->parse($code);
3441 $this->importCache
[$realPath] = $tree;
3444 $pi = pathinfo($path);
3445 array_unshift($this->importPaths
, $pi['dirname']);
3446 $this->compileChildrenNoReturn($tree->children
, $out);
3447 array_shift($this->importPaths
);
3451 * Return the file path for an import url if it exists
3455 * @param string $url
3457 * @return string|null
3459 public function findImport($url)
3463 // for "normal" scss imports (ignore vanilla css and external requests)
3464 if (! preg_match('/\.css$|^https?:\/\//', $url)) {
3465 // try both normal and the _partial filename
3466 $urls = [$url, preg_replace('/[^\/]+$/', '_\0', $url)];
3469 $hasExtension = preg_match('/[.]s?css$/', $url);
3471 foreach ($this->importPaths
as $dir) {
3472 if (is_string($dir)) {
3473 // check urls for normal import paths
3474 foreach ($urls as $full) {
3476 . (! empty($dir) && substr($dir, -1) !== '/' ?
'/' : '')
3479 if ($this->fileExists($file = $full . '.scss') ||
3480 ($hasExtension && $this->fileExists($file = $full))
3485 } elseif (is_callable($dir)) {
3486 // check custom callback for import path
3487 $file = call_user_func($dir, $url);
3489 if ($file !== null) {
3503 * @param string $encoding
3505 public function setEncoding($encoding)
3507 $this->encoding
= $encoding;
3515 * @param boolean $ignoreErrors
3517 * @return \Leafo\ScssPhp\Compiler
3519 public function setIgnoreErrors($ignoreErrors)
3521 $this->ignoreErrors
= $ignoreErrors;
3525 * Throw error (exception)
3529 * @param string $msg Message with optional sprintf()-style vararg parameters
3531 * @throws \Leafo\ScssPhp\Exception\CompilerException
3533 public function throwError($msg)
3535 if ($this->ignoreErrors
) {
3539 if (func_num_args() > 1) {
3540 $msg = call_user_func_array('sprintf', func_get_args());
3543 $line = $this->sourceLine
;
3544 $msg = "$msg: line: $line";
3546 throw new CompilerException($msg);
3550 * Handle import loop
3552 * @param string $name
3554 * @throws \Exception
3556 protected function handleImportLoop($name)
3558 for ($env = $this->env
; $env; $env = $env->parent
) {
3559 $file = $this->sourceNames
[$env->block
->sourceIndex
];
3561 if (realpath($file) === $name) {
3562 $this->throwError('An @import loop has been found: %s imports %s', $file, basename($file));
3571 * @param string $name
3575 protected function fileExists($name)
3577 return file_exists($name) && is_file($name);
3581 * Call SCSS @function
3583 * @param string $name
3584 * @param array $argValues
3585 * @param array $returnValue
3587 * @return boolean Returns true if returnValue is set; otherwise, false
3589 protected function callScssFunction($name, $argValues, &$returnValue)
3591 $func = $this->get(static::$namespaces['function'] . $name, false);
3599 $storeEnv = $this->storeEnv
;
3600 $this->storeEnv
= $this->env
;
3603 if (isset($func->args
)) {
3604 $this->applyArguments($func->args
, $argValues);
3607 // throw away lines and children
3608 $tmp = new OutputBlock
;
3610 $tmp->children
= [];
3612 $this->env
->marker
= 'function';
3614 $ret = $this->compileChildren($func->children
, $tmp);
3616 $this->storeEnv
= $storeEnv;
3620 $returnValue = ! isset($ret) ?
static::$defaultValue : $ret;
3626 * Call built-in and registered (PHP) functions
3628 * @param string $name
3629 * @param array $args
3630 * @param array $returnValue
3632 * @return boolean Returns true if returnValue is set; otherwise, false
3634 protected function callNativeFunction($name, $args, &$returnValue)
3636 // try a lib function
3637 $name = $this->normalizeName($name);
3639 if (isset($this->userFunctions
[$name])) {
3640 // see if we can find a user function
3641 list($f, $prototype) = $this->userFunctions
[$name];
3642 } elseif (($f = $this->getBuiltinFunction($name)) && is_callable($f)) {
3644 $prototype = isset(static::$
$libName) ?
static::$
$libName : null;
3649 list($sorted, $kwargs) = $this->sortArgs($prototype, $args);
3651 if ($name !== 'if' && $name !== 'call') {
3652 foreach ($sorted as &$val) {
3653 $val = $this->reduce($val, true);
3657 $returnValue = call_user_func($f, $sorted, $kwargs);
3659 if (! isset($returnValue)) {
3663 $returnValue = $this->coerceValue($returnValue);
3669 * Get built-in function
3671 * @param string $name Normalized name
3675 protected function getBuiltinFunction($name)
3677 $libName = 'lib' . preg_replace_callback(
3680 return ucfirst($m[1]);
3685 return [$this, $libName];
3689 * Sorts keyword arguments
3691 * @param array $prototype
3692 * @param array $args
3696 protected function sortArgs($prototype, $args)
3701 // separate positional and keyword arguments
3702 foreach ($args as $arg) {
3703 list($key, $value) = $arg;
3708 $posArgs[] = $value;
3710 $keyArgs[$key] = $value;
3714 if (! isset($prototype)) {
3715 return [$posArgs, $keyArgs];
3718 // copy positional args
3719 $finalArgs = array_pad($posArgs, count($prototype), null);
3721 // overwrite positional args with keyword args
3722 foreach ($prototype as $i => $names) {
3723 foreach ((array) $names as $name) {
3724 if (isset($keyArgs[$name])) {
3725 $finalArgs[$i] = $keyArgs[$name];
3730 return [$finalArgs, $keyArgs];
3734 * Apply argument values per definition
3736 * @param array $argDef
3737 * @param array $argValues
3739 * @throws \Exception
3741 protected function applyArguments($argDef, $argValues)
3743 $storeEnv = $this->getStoreEnv();
3745 $env = new Environment
;
3746 $env->store
= $storeEnv->store
;
3748 $hasVariable = false;
3751 foreach ($argDef as $i => $arg) {
3752 list($name, $default, $isVariable) = $argDef[$i];
3754 $args[$name] = [$i, $name, $default, $isVariable];
3755 $hasVariable |
= $isVariable;
3759 $deferredKeywordArgs = [];
3762 // assign the keyword args
3763 foreach ((array) $argValues as $arg) {
3764 if (! empty($arg[0])) {
3765 if (! isset($args[$arg[0][1]])) {
3767 $deferredKeywordArgs[$arg[0][1]] = $arg[1];
3769 $this->throwError("Mixin or function doesn't have an argument named $%s.", $arg[0][1]);
3772 } elseif ($args[$arg[0][1]][0] < count($remaining)) {
3773 $this->throwError("The argument $%s was passed both by position and by name.", $arg[0][1]);
3776 $keywordArgs[$arg[0][1]] = $arg[1];
3778 } elseif (count($keywordArgs)) {
3779 $this->throwError('Positional arguments must come before keyword arguments.');
3781 } elseif ($arg[2] === true) {
3782 $val = $this->reduce($arg[1], true);
3784 if ($val[0] === Type
::T_LIST
) {
3785 foreach ($val[2] as $name => $item) {
3786 if (! is_numeric($name)) {
3787 $keywordArgs[$name] = $item;
3789 $remaining[] = $item;
3792 } elseif ($val[0] === Type
::T_MAP
) {
3793 foreach ($val[1] as $i => $name) {
3794 $name = $this->compileStringContent($this->coerceString($name));
3795 $item = $val[2][$i];
3797 if (! is_numeric($name)) {
3798 $keywordArgs[$name] = $item;
3800 $remaining[] = $item;
3804 $remaining[] = $val;
3807 $remaining[] = $arg[1];
3811 foreach ($args as $arg) {
3812 list($i, $name, $default, $isVariable) = $arg;
3815 $val = [Type
::T_LIST
, ',', [], $isVariable];
3817 for ($count = count($remaining); $i < $count; $i++
) {
3818 $val[2][] = $remaining[$i];
3821 foreach ($deferredKeywordArgs as $itemName => $item) {
3822 $val[2][$itemName] = $item;
3824 } elseif (isset($remaining[$i])) {
3825 $val = $remaining[$i];
3826 } elseif (isset($keywordArgs[$name])) {
3827 $val = $keywordArgs[$name];
3828 } elseif (! empty($default)) {
3831 $this->throwError("Missing argument $name");
3835 $this->set($name, $this->reduce($val, true), true, $env);
3838 $storeEnv->store
= $env->store
;
3840 foreach ($args as $arg) {
3841 list($i, $name, $default, $isVariable) = $arg;
3843 if ($isVariable ||
isset($remaining[$i]) ||
isset($keywordArgs[$name]) ||
empty($default)) {
3847 $this->set($name, $this->reduce($default, true), true);
3852 * Coerce a php value into a scss one
3854 * @param mixed $value
3856 * @return array|\Leafo\ScssPhp\Node\Number
3858 private function coerceValue($value)
3860 if (is_array($value) ||
$value instanceof \ArrayAccess
) {
3864 if (is_bool($value)) {
3865 return $this->toBool($value);
3868 if ($value === null) {
3869 return static::$null;
3872 if (is_numeric($value)) {
3873 return new Node\
Number($value, '');
3876 if ($value === '') {
3877 return static::$emptyString;
3880 if (preg_match('/^(#([0-9a-f]{6})|#([0-9a-f]{3}))$/i', $value, $m)) {
3881 $color = [Type
::T_COLOR
];
3884 $num = hexdec($m[3]);
3886 foreach ([3, 2, 1] as $i) {
3888 $color[$i] = $t << 4 |
$t;
3892 $num = hexdec($m[2]);
3894 foreach ([3, 2, 1] as $i) {
3895 $color[$i] = $num & 0xff;
3903 return [Type
::T_KEYWORD
, $value];
3907 * Coerce something to map
3909 * @param array $item
3913 protected function coerceMap($item)
3915 if ($item[0] === Type
::T_MAP
) {
3919 if ($item === static::$emptyList) {
3920 return static::$emptyMap;
3923 return [Type
::T_MAP
, [$item], [static::$null]];
3927 * Coerce something to list
3929 * @param array $item
3930 * @param string $delim
3934 protected function coerceList($item, $delim = ',')
3936 if (isset($item) && $item[0] === Type
::T_LIST
) {
3940 if (isset($item) && $item[0] === Type
::T_MAP
) {
3945 for ($i = 0, $s = count($keys); $i < $s; $i++
) {
3947 $value = $values[$i];
3952 [[Type
::T_KEYWORD
, $this->compileStringContent($this->coerceString($key))], $value]
3956 return [Type
::T_LIST
, ',', $list];
3959 return [Type
::T_LIST
, $delim, ! isset($item) ?
[]: [$item]];
3963 * Coerce color for expression
3965 * @param array $value
3967 * @return array|null
3969 protected function coerceForExpression($value)
3971 if ($color = $this->coerceColor($value)) {
3979 * Coerce value to color
3981 * @param array $value
3983 * @return array|null
3985 protected function coerceColor($value)
3987 switch ($value[0]) {
3991 case Type
::T_KEYWORD
:
3992 $name = strtolower($value[1]);
3994 if (isset(Colors
::$cssColors[$name])) {
3995 $rgba = explode(',', Colors
::$cssColors[$name]);
3997 return isset($rgba[3])
3998 ?
[Type
::T_COLOR
, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2], (int) $rgba[3]]
3999 : [Type
::T_COLOR
, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2]];
4009 * Coerce value to string
4011 * @param array $value
4013 * @return array|null
4015 protected function coerceString($value)
4017 if ($value[0] === Type
::T_STRING
) {
4021 return [Type
::T_STRING
, '', [$this->compileValue($value)]];
4025 * Coerce value to a percentage
4027 * @param array $value
4029 * @return integer|float
4031 protected function coercePercent($value)
4033 if ($value[0] === Type
::T_NUMBER
) {
4034 if (! empty($value[2]['%'])) {
4035 return $value[1] / 100;
4045 * Assert value is a map
4049 * @param array $value
4053 * @throws \Exception
4055 public function assertMap($value)
4057 $value = $this->coerceMap($value);
4059 if ($value[0] !== Type
::T_MAP
) {
4060 $this->throwError('expecting map');
4067 * Assert value is a list
4071 * @param array $value
4075 * @throws \Exception
4077 public function assertList($value)
4079 if ($value[0] !== Type
::T_LIST
) {
4080 $this->throwError('expecting list');
4087 * Assert value is a color
4091 * @param array $value
4095 * @throws \Exception
4097 public function assertColor($value)
4099 if ($color = $this->coerceColor($value)) {
4103 $this->throwError('expecting color');
4107 * Assert value is a number
4111 * @param array $value
4113 * @return integer|float
4115 * @throws \Exception
4117 public function assertNumber($value)
4119 if ($value[0] !== Type
::T_NUMBER
) {
4120 $this->throwError('expecting number');
4127 * Make sure a color's components don't go out of bounds
4133 protected function fixColor($c)
4135 foreach ([1, 2, 3] as $i) {
4149 * Convert RGB to HSL
4153 * @param integer $red
4154 * @param integer $green
4155 * @param integer $blue
4159 public function toHSL($red, $green, $blue)
4161 $min = min($red, $green, $blue);
4162 $max = max($red, $green, $blue);
4167 if ((int) $d === 0) {
4173 $s = $d / (510 - $l);
4177 $h = 60 * ($green - $blue) / $d;
4178 } elseif ($green == $max) {
4179 $h = 60 * ($blue - $red) / $d +
120;
4180 } elseif ($blue == $max) {
4181 $h = 60 * ($red - $green) / $d +
240;
4185 return [Type
::T_HSL
, fmod($h, 360), $s * 100, $l / 5.1];
4197 private function hueToRGB($m1, $m2, $h)
4206 return $m1 +
($m2 - $m1) * $h * 6;
4214 return $m1 +
($m2 - $m1) * (2/3 - $h) * 6;
4221 * Convert HSL to RGB
4225 * @param integer $hue H from 0 to 360
4226 * @param integer $saturation S from 0 to 100
4227 * @param integer $lightness L from 0 to 100
4231 public function toRGB($hue, $saturation, $lightness)
4238 $s = min(100, max(0, $saturation)) / 100;
4239 $l = min(100, max(0, $lightness)) / 100;
4241 $m2 = $l <= 0.5 ?
$l * ($s +
1) : $l +
$s - $l * $s;
4244 $r = $this->hueToRGB($m1, $m2, $h +
1/3) * 255;
4245 $g = $this->hueToRGB($m1, $m2, $h) * 255;
4246 $b = $this->hueToRGB($m1, $m2, $h - 1/3) * 255;
4248 $out = [Type
::T_COLOR
, $r, $g, $b];
4253 // Built in functions
4255 //protected static $libCall = ['name', 'args...'];
4256 protected function libCall($args, $kwargs)
4258 $name = $this->compileStringContent($this->coerceString($this->reduce(array_shift($args), true)));
4262 return [null, $a, false];
4267 if (count($kwargs)) {
4268 foreach ($kwargs as $key => $value) {
4269 $args[] = [[Type
::T_VARIABLE
, $key], $value, false];
4273 return $this->reduce([Type
::T_FUNCTION_CALL
, $name, $args]);
4276 protected static $libIf = ['condition', 'if-true', 'if-false'];
4277 protected function libIf($args)
4279 list($cond, $t, $f) = $args;
4281 if (! $this->isTruthy($this->reduce($cond, true))) {
4282 return $this->reduce($f, true);
4285 return $this->reduce($t, true);
4288 protected static $libIndex = ['list', 'value'];
4289 protected function libIndex($args)
4291 list($list, $value) = $args;
4293 if ($value[0] === Type
::T_MAP
) {
4294 return static::$null;
4297 if ($list[0] === Type
::T_MAP ||
4298 $list[0] === Type
::T_STRING ||
4299 $list[0] === Type
::T_KEYWORD ||
4300 $list[0] === Type
::T_INTERPOLATE
4302 $list = $this->coerceList($list, ' ');
4305 if ($list[0] !== Type
::T_LIST
) {
4306 return static::$null;
4311 foreach ($list[2] as $item) {
4312 $values[] = $this->normalizeValue($item);
4315 $key = array_search($this->normalizeValue($value), $values);
4317 return false === $key ?
static::$null : $key +
1;
4320 protected static $libRgb = ['red', 'green', 'blue'];
4321 protected function libRgb($args)
4323 list($r, $g, $b) = $args;
4325 return [Type
::T_COLOR
, $r[1], $g[1], $b[1]];
4328 protected static $libRgba = [
4330 'green', 'blue', 'alpha'];
4331 protected function libRgba($args)
4333 if ($color = $this->coerceColor($args[0])) {
4334 $num = ! isset($args[1]) ?
$args[3] : $args[1];
4335 $alpha = $this->assertNumber($num);
4341 list($r, $g, $b, $a) = $args;
4343 return [Type
::T_COLOR
, $r[1], $g[1], $b[1], $a[1]];
4346 // helper function for adjust_color, change_color, and scale_color
4347 protected function alterColor($args, $fn)
4349 $color = $this->assertColor($args[0]);
4351 foreach ([1, 2, 3, 7] as $i) {
4352 if (isset($args[$i])) {
4353 $val = $this->assertNumber($args[$i]);
4354 $ii = $i === 7 ?
4 : $i; // alpha
4355 $color[$ii] = call_user_func($fn, isset($color[$ii]) ?
$color[$ii] : 0, $val, $i);
4359 if (isset($args[4]) ||
isset($args[5]) ||
isset($args[6])) {
4360 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4362 foreach ([4, 5, 6] as $i) {
4363 if (isset($args[$i])) {
4364 $val = $this->assertNumber($args[$i]);
4365 $hsl[$i - 3] = call_user_func($fn, $hsl[$i - 3], $val, $i);
4369 $rgb = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
4371 if (isset($color[4])) {
4372 $rgb[4] = $color[4];
4381 protected static $libAdjustColor = [
4382 'color', 'red', 'green', 'blue',
4383 'hue', 'saturation', 'lightness', 'alpha'
4385 protected function libAdjustColor($args)
4387 return $this->alterColor($args, function ($base, $alter, $i) {
4388 return $base +
$alter;
4392 protected static $libChangeColor = [
4393 'color', 'red', 'green', 'blue',
4394 'hue', 'saturation', 'lightness', 'alpha'
4396 protected function libChangeColor($args)
4398 return $this->alterColor($args, function ($base, $alter, $i) {
4403 protected static $libScaleColor = [
4404 'color', 'red', 'green', 'blue',
4405 'hue', 'saturation', 'lightness', 'alpha'
4407 protected function libScaleColor($args)
4409 return $this->alterColor($args, function ($base, $scale, $i) {
4432 $scale = $scale / 100;
4435 return $base * $scale +
$base;
4438 return ($max - $base) * $scale +
$base;
4442 protected static $libIeHexStr = ['color'];
4443 protected function libIeHexStr($args)
4445 $color = $this->coerceColor($args[0]);
4446 $color[4] = isset($color[4]) ?
round(255 * $color[4]) : 255;
4448 return sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3]);
4451 protected static $libRed = ['color'];
4452 protected function libRed($args)
4454 $color = $this->coerceColor($args[0]);
4459 protected static $libGreen = ['color'];
4460 protected function libGreen($args)
4462 $color = $this->coerceColor($args[0]);
4467 protected static $libBlue = ['color'];
4468 protected function libBlue($args)
4470 $color = $this->coerceColor($args[0]);
4475 protected static $libAlpha = ['color'];
4476 protected function libAlpha($args)
4478 if ($color = $this->coerceColor($args[0])) {
4479 return isset($color[4]) ?
$color[4] : 1;
4482 // this might be the IE function, so return value unchanged
4486 protected static $libOpacity = ['color'];
4487 protected function libOpacity($args)
4491 if ($value[0] === Type
::T_NUMBER
) {
4495 return $this->libAlpha($args);
4499 protected static $libMix = ['color-1', 'color-2', 'weight'];
4500 protected function libMix($args)
4502 list($first, $second, $weight) = $args;
4504 $first = $this->assertColor($first);
4505 $second = $this->assertColor($second);
4507 if (! isset($weight)) {
4510 $weight = $this->coercePercent($weight);
4513 $firstAlpha = isset($first[4]) ?
$first[4] : 1;
4514 $secondAlpha = isset($second[4]) ?
$second[4] : 1;
4516 $w = $weight * 2 - 1;
4517 $a = $firstAlpha - $secondAlpha;
4519 $w1 = (($w * $a === -1 ?
$w : ($w +
$a) / (1 +
$w * $a)) +
1) / 2.0;
4522 $new = [Type
::T_COLOR
,
4523 $w1 * $first[1] +
$w2 * $second[1],
4524 $w1 * $first[2] +
$w2 * $second[2],
4525 $w1 * $first[3] +
$w2 * $second[3],
4528 if ($firstAlpha != 1.0 ||
$secondAlpha != 1.0) {
4529 $new[] = $firstAlpha * $weight +
$secondAlpha * ($weight - 1);
4532 return $this->fixColor($new);
4535 protected static $libHsl = ['hue', 'saturation', 'lightness'];
4536 protected function libHsl($args)
4538 list($h, $s, $l) = $args;
4540 return $this->toRGB($h[1], $s[1], $l[1]);
4543 protected static $libHsla = ['hue', 'saturation', 'lightness', 'alpha'];
4544 protected function libHsla($args)
4546 list($h, $s, $l, $a) = $args;
4548 $color = $this->toRGB($h[1], $s[1], $l[1]);
4554 protected static $libHue = ['color'];
4555 protected function libHue($args)
4557 $color = $this->assertColor($args[0]);
4558 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4560 return new Node\
Number($hsl[1], 'deg');
4563 protected static $libSaturation = ['color'];
4564 protected function libSaturation($args)
4566 $color = $this->assertColor($args[0]);
4567 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4569 return new Node\
Number($hsl[2], '%');
4572 protected static $libLightness = ['color'];
4573 protected function libLightness($args)
4575 $color = $this->assertColor($args[0]);
4576 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4578 return new Node\
Number($hsl[3], '%');
4581 protected function adjustHsl($color, $idx, $amount)
4583 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4584 $hsl[$idx] +
= $amount;
4585 $out = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
4587 if (isset($color[4])) {
4588 $out[4] = $color[4];
4594 protected static $libAdjustHue = ['color', 'degrees'];
4595 protected function libAdjustHue($args)
4597 $color = $this->assertColor($args[0]);
4598 $degrees = $this->assertNumber($args[1]);
4600 return $this->adjustHsl($color, 1, $degrees);
4603 protected static $libLighten = ['color', 'amount'];
4604 protected function libLighten($args)
4606 $color = $this->assertColor($args[0]);
4607 $amount = Util
::checkRange('amount', new Range(0, 100), $args[1], '%');
4609 return $this->adjustHsl($color, 3, $amount);
4612 protected static $libDarken = ['color', 'amount'];
4613 protected function libDarken($args)
4615 $color = $this->assertColor($args[0]);
4616 $amount = Util
::checkRange('amount', new Range(0, 100), $args[1], '%');
4618 return $this->adjustHsl($color, 3, -$amount);
4621 protected static $libSaturate = ['color', 'amount'];
4622 protected function libSaturate($args)
4626 if ($value[0] === Type
::T_NUMBER
) {
4630 $color = $this->assertColor($value);
4631 $amount = 100 * $this->coercePercent($args[1]);
4633 return $this->adjustHsl($color, 2, $amount);
4636 protected static $libDesaturate = ['color', 'amount'];
4637 protected function libDesaturate($args)
4639 $color = $this->assertColor($args[0]);
4640 $amount = 100 * $this->coercePercent($args[1]);
4642 return $this->adjustHsl($color, 2, -$amount);
4645 protected static $libGrayscale = ['color'];
4646 protected function libGrayscale($args)
4650 if ($value[0] === Type
::T_NUMBER
) {
4654 return $this->adjustHsl($this->assertColor($value), 2, -100);
4657 protected static $libComplement = ['color'];
4658 protected function libComplement($args)
4660 return $this->adjustHsl($this->assertColor($args[0]), 1, 180);
4663 protected static $libInvert = ['color'];
4664 protected function libInvert($args)
4668 if ($value[0] === Type
::T_NUMBER
) {
4672 $color = $this->assertColor($value);
4673 $color[1] = 255 - $color[1];
4674 $color[2] = 255 - $color[2];
4675 $color[3] = 255 - $color[3];
4680 // increases opacity by amount
4681 protected static $libOpacify = ['color', 'amount'];
4682 protected function libOpacify($args)
4684 $color = $this->assertColor($args[0]);
4685 $amount = $this->coercePercent($args[1]);
4687 $color[4] = (isset($color[4]) ?
$color[4] : 1) +
$amount;
4688 $color[4] = min(1, max(0, $color[4]));
4693 protected static $libFadeIn = ['color', 'amount'];
4694 protected function libFadeIn($args)
4696 return $this->libOpacify($args);
4699 // decreases opacity by amount
4700 protected static $libTransparentize = ['color', 'amount'];
4701 protected function libTransparentize($args)
4703 $color = $this->assertColor($args[0]);
4704 $amount = $this->coercePercent($args[1]);
4706 $color[4] = (isset($color[4]) ?
$color[4] : 1) - $amount;
4707 $color[4] = min(1, max(0, $color[4]));
4712 protected static $libFadeOut = ['color', 'amount'];
4713 protected function libFadeOut($args)
4715 return $this->libTransparentize($args);
4718 protected static $libUnquote = ['string'];
4719 protected function libUnquote($args)
4723 if ($str[0] === Type
::T_STRING
) {
4730 protected static $libQuote = ['string'];
4731 protected function libQuote($args)
4735 if ($value[0] === Type
::T_STRING
&& ! empty($value[1])) {
4739 return [Type
::T_STRING
, '"', [$value]];
4742 protected static $libPercentage = ['value'];
4743 protected function libPercentage($args)
4745 return new Node\
Number($this->coercePercent($args[0]) * 100, '%');
4748 protected static $libRound = ['value'];
4749 protected function libRound($args)
4753 return new Node\
Number(round($num[1]), $num[2]);
4756 protected static $libFloor = ['value'];
4757 protected function libFloor($args)
4761 return new Node\
Number(floor($num[1]), $num[2]);
4764 protected static $libCeil = ['value'];
4765 protected function libCeil($args)
4769 return new Node\
Number(ceil($num[1]), $num[2]);
4772 protected static $libAbs = ['value'];
4773 protected function libAbs($args)
4777 return new Node\
Number(abs($num[1]), $num[2]);
4780 protected function libMin($args)
4782 $numbers = $this->getNormalizedNumbers($args);
4785 foreach ($numbers as $key => $number) {
4786 if (null === $min ||
$number[1] <= $min[1]) {
4787 $min = [$key, $number[1]];
4791 return $args[$min[0]];
4794 protected function libMax($args)
4796 $numbers = $this->getNormalizedNumbers($args);
4799 foreach ($numbers as $key => $number) {
4800 if (null === $max ||
$number[1] >= $max[1]) {
4801 $max = [$key, $number[1]];
4805 return $args[$max[0]];
4809 * Helper to normalize args containing numbers
4811 * @param array $args
4815 protected function getNormalizedNumbers($args)
4818 $originalUnit = null;
4821 foreach ($args as $key => $item) {
4822 if ($item[0] !== Type
::T_NUMBER
) {
4823 $this->throwError('%s is not a number', $item[0]);
4827 $number = $item->normalize();
4829 if (null === $unit) {
4831 $originalUnit = $item->unitStr();
4832 } elseif ($unit !== $number[2]) {
4833 $this->throwError('Incompatible units: "%s" and "%s".', $originalUnit, $item->unitStr());
4837 $numbers[$key] = $number;
4843 protected static $libLength = ['list'];
4844 protected function libLength($args)
4846 $list = $this->coerceList($args[0]);
4848 return count($list[2]);
4851 //protected static $libListSeparator = ['list...'];
4852 protected function libListSeparator($args)
4854 if (count($args) > 1) {
4858 $list = $this->coerceList($args[0]);
4860 if (count($list[2]) <= 1) {
4864 if ($list[1] === ',') {
4871 protected static $libNth = ['list', 'n'];
4872 protected function libNth($args)
4874 $list = $this->coerceList($args[0]);
4875 $n = $this->assertNumber($args[1]);
4880 $n +
= count($list[2]);
4883 return isset($list[2][$n]) ?
$list[2][$n] : static::$defaultValue;
4886 protected static $libSetNth = ['list', 'n', 'value'];
4887 protected function libSetNth($args)
4889 $list = $this->coerceList($args[0]);
4890 $n = $this->assertNumber($args[1]);
4895 $n +
= count($list[2]);
4898 if (! isset($list[2][$n])) {
4899 $this->throwError('Invalid argument for "n"');
4904 $list[2][$n] = $args[2];
4909 protected static $libMapGet = ['map', 'key'];
4910 protected function libMapGet($args)
4912 $map = $this->assertMap($args[0]);
4913 $key = $this->compileStringContent($this->coerceString($args[1]));
4915 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
4916 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
4921 return static::$null;
4924 protected static $libMapKeys = ['map'];
4925 protected function libMapKeys($args)
4927 $map = $this->assertMap($args[0]);
4930 return [Type
::T_LIST
, ',', $keys];
4933 protected static $libMapValues = ['map'];
4934 protected function libMapValues($args)
4936 $map = $this->assertMap($args[0]);
4939 return [Type
::T_LIST
, ',', $values];
4942 protected static $libMapRemove = ['map', 'key'];
4943 protected function libMapRemove($args)
4945 $map = $this->assertMap($args[0]);
4946 $key = $this->compileStringContent($this->coerceString($args[1]));
4948 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
4949 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
4950 array_splice($map[1], $i, 1);
4951 array_splice($map[2], $i, 1);
4958 protected static $libMapHasKey = ['map', 'key'];
4959 protected function libMapHasKey($args)
4961 $map = $this->assertMap($args[0]);
4962 $key = $this->compileStringContent($this->coerceString($args[1]));
4964 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
4965 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
4973 protected static $libMapMerge = ['map-1', 'map-2'];
4974 protected function libMapMerge($args)
4976 $map1 = $this->assertMap($args[0]);
4977 $map2 = $this->assertMap($args[1]);
4979 return [Type
::T_MAP
, array_merge($map1[1], $map2[1]), array_merge($map1[2], $map2[2])];
4982 protected static $libKeywords = ['args'];
4983 protected function libKeywords($args)
4985 $this->assertList($args[0]);
4990 foreach ($args[0][2] as $name => $arg) {
4991 $keys[] = [Type
::T_KEYWORD
, $name];
4995 return [Type
::T_MAP
, $keys, $values];
4998 protected function listSeparatorForJoin($list1, $sep)
5000 if (! isset($sep)) {
5004 switch ($this->compileValue($sep)) {
5016 protected static $libJoin = ['list1', 'list2', 'separator'];
5017 protected function libJoin($args)
5019 list($list1, $list2, $sep) = $args;
5021 $list1 = $this->coerceList($list1, ' ');
5022 $list2 = $this->coerceList($list2, ' ');
5023 $sep = $this->listSeparatorForJoin($list1, $sep);
5025 return [Type
::T_LIST
, $sep, array_merge($list1[2], $list2[2])];
5028 protected static $libAppend = ['list', 'val', 'separator'];
5029 protected function libAppend($args)
5031 list($list1, $value, $sep) = $args;
5033 $list1 = $this->coerceList($list1, ' ');
5034 $sep = $this->listSeparatorForJoin($list1, $sep);
5036 return [Type
::T_LIST
, $sep, array_merge($list1[2], [$value])];
5039 protected function libZip($args)
5041 foreach ($args as $arg) {
5042 $this->assertList($arg);
5046 $firstList = array_shift($args);
5048 foreach ($firstList[2] as $key => $item) {
5049 $list = [Type
::T_LIST
, '', [$item]];
5051 foreach ($args as $arg) {
5052 if (isset($arg[2][$key])) {
5053 $list[2][] = $arg[2][$key];
5062 return [Type
::T_LIST
, ',', $lists];
5065 protected static $libTypeOf = ['value'];
5066 protected function libTypeOf($args)
5070 switch ($value[0]) {
5071 case Type
::T_KEYWORD
:
5072 if ($value === static::$true ||
$value === static::$false) {
5076 if ($this->coerceColor($value)) {
5081 case Type
::T_FUNCTION
:
5085 if (isset($value[3]) && $value[3]) {
5095 protected static $libUnit = ['number'];
5096 protected function libUnit($args)
5100 if ($num[0] === Type
::T_NUMBER
) {
5101 return [Type
::T_STRING
, '"', [$num->unitStr()]];
5107 protected static $libUnitless = ['number'];
5108 protected function libUnitless($args)
5112 return $value[0] === Type
::T_NUMBER
&& $value->unitless();
5115 protected static $libComparable = ['number-1', 'number-2'];
5116 protected function libComparable($args)
5118 list($number1, $number2) = $args;
5120 if (! isset($number1[0]) ||
$number1[0] !== Type
::T_NUMBER ||
5121 ! isset($number2[0]) ||
$number2[0] !== Type
::T_NUMBER
5123 $this->throwError('Invalid argument(s) for "comparable"');
5128 $number1 = $number1->normalize();
5129 $number2 = $number2->normalize();
5131 return $number1[2] === $number2[2] ||
$number1->unitless() ||
$number2->unitless();
5134 protected static $libStrIndex = ['string', 'substring'];
5135 protected function libStrIndex($args)
5137 $string = $this->coerceString($args[0]);
5138 $stringContent = $this->compileStringContent($string);
5140 $substring = $this->coerceString($args[1]);
5141 $substringContent = $this->compileStringContent($substring);
5143 $result = strpos($stringContent, $substringContent);
5145 return $result === false ?
static::$null : new Node\
Number($result +
1, '');
5148 protected static $libStrInsert = ['string', 'insert', 'index'];
5149 protected function libStrInsert($args)
5151 $string = $this->coerceString($args[0]);
5152 $stringContent = $this->compileStringContent($string);
5154 $insert = $this->coerceString($args[1]);
5155 $insertContent = $this->compileStringContent($insert);
5157 list(, $index) = $args[2];
5159 $string[2] = [substr_replace($stringContent, $insertContent, $index - 1, 0)];
5164 protected static $libStrLength = ['string'];
5165 protected function libStrLength($args)
5167 $string = $this->coerceString($args[0]);
5168 $stringContent = $this->compileStringContent($string);
5170 return new Node\
Number(strlen($stringContent), '');
5173 protected static $libStrSlice = ['string', 'start-at', 'end-at'];
5174 protected function libStrSlice($args)
5176 if (isset($args[2]) && $args[2][1] == 0) {
5177 return static::$nullString;
5180 $string = $this->coerceString($args[0]);
5181 $stringContent = $this->compileStringContent($string);
5183 $start = (int) $args[1][1];
5189 $end = (int) $args[2][1];
5190 $length = $end < 0 ?
$end +
1 : ($end > 0 ?
$end - $start : $end);
5192 $string[2] = $length
5193 ?
[substr($stringContent, $start, $length)]
5194 : [substr($stringContent, $start)];
5199 protected static $libToLowerCase = ['string'];
5200 protected function libToLowerCase($args)
5202 $string = $this->coerceString($args[0]);
5203 $stringContent = $this->compileStringContent($string);
5205 $string[2] = [function_exists('mb_strtolower') ?
mb_strtolower($stringContent) : strtolower($stringContent)];
5210 protected static $libToUpperCase = ['string'];
5211 protected function libToUpperCase($args)
5213 $string = $this->coerceString($args[0]);
5214 $stringContent = $this->compileStringContent($string);
5216 $string[2] = [function_exists('mb_strtoupper') ?
mb_strtoupper($stringContent) : strtoupper($stringContent)];
5221 protected static $libFeatureExists = ['feature'];
5222 protected function libFeatureExists($args)
5224 $string = $this->coerceString($args[0]);
5225 $name = $this->compileStringContent($string);
5227 return $this->toBool(
5228 array_key_exists($name, $this->registeredFeatures
) ?
$this->registeredFeatures
[$name] : false
5232 protected static $libFunctionExists = ['name'];
5233 protected function libFunctionExists($args)
5235 $string = $this->coerceString($args[0]);
5236 $name = $this->compileStringContent($string);
5238 // user defined functions
5239 if ($this->has(static::$namespaces['function'] . $name)) {
5243 $name = $this->normalizeName($name);
5245 if (isset($this->userFunctions
[$name])) {
5249 // built-in functions
5250 $f = $this->getBuiltinFunction($name);
5252 return $this->toBool(is_callable($f));
5255 protected static $libGlobalVariableExists = ['name'];
5256 protected function libGlobalVariableExists($args)
5258 $string = $this->coerceString($args[0]);
5259 $name = $this->compileStringContent($string);
5261 return $this->has($name, $this->rootEnv
);
5264 protected static $libMixinExists = ['name'];
5265 protected function libMixinExists($args)
5267 $string = $this->coerceString($args[0]);
5268 $name = $this->compileStringContent($string);
5270 return $this->has(static::$namespaces['mixin'] . $name);
5273 protected static $libVariableExists = ['name'];
5274 protected function libVariableExists($args)
5276 $string = $this->coerceString($args[0]);
5277 $name = $this->compileStringContent($string);
5279 return $this->has($name);
5283 * Workaround IE7's content counter bug.
5285 * @param array $args
5289 protected function libCounter($args)
5291 $list = array_map([$this, 'compileValue'], $args);
5293 return [Type
::T_STRING
, '', ['counter(' . implode(',', $list) . ')']];
5296 protected static $libRandom = ['limit'];
5297 protected function libRandom($args)
5299 if (isset($args[0])) {
5300 $n = $this->assertNumber($args[0]);
5303 $this->throwError("limit must be greater than or equal to 1");
5308 return new Node\
Number(mt_rand(1, $n), '');
5311 return new Node\
Number(mt_rand(1, mt_getrandmax()), '');
5314 protected function libUniqueId()
5319 $id = mt_rand(0, pow(36, 8));
5322 $id +
= mt_rand(0, 10) +
1;
5324 return [Type
::T_STRING
, '', ['u' . str_pad(base_convert($id, 10, 36), 8, '0', STR_PAD_LEFT
)]];
5327 protected static $libInspect = ['value'];
5328 protected function libInspect($args)
5330 if ($args[0] === static::$null) {
5331 return [Type
::T_KEYWORD
, 'null'];