5 * @copyright 2012-2018 Leaf Corcoran
7 * @license http://opensource.org/licenses/MIT MIT
9 * @link http://leafo.github.io/scssphp
16 * The scss compiler and parser.
18 * Converting SCSS to CSS is a three stage process. The incoming file is parsed
19 * by `Parser` into a syntax tree, then it is compiled into another tree
20 * representing the CSS structure by `Compiler`. The CSS tree is fed into a
21 * formatter, like `Formatter` which then outputs CSS as a string.
23 * During the first compile, all values are *reduced*, which means that their
24 * types are brought to the lowest form before being dump as strings. This
25 * handles math equations, variable dereferences, and the like.
27 * The `compile` function of `Compiler` is the entry point.
31 * The `Compiler` class creates an instance of the parser, feeds it SCSS code,
32 * then transforms the resulting tree to a CSS tree. This class also holds the
33 * evaluation context, such as all available mixins and variables at any given
36 * The `Parser` class is only concerned with parsing its input.
38 * The `Formatter` takes a CSS tree, and dumps it to a formatted string,
39 * handling things like indentation.
41 require_once 'Scss/Type.php';
42 require_once 'Scss/Util.php';
43 require_once 'Scss/Block.php';
44 require_once 'Scss/Parser.php';
45 require_once 'Scss/Colors.php';
46 require_once 'Scss/Compiler/Environment.php';
47 require_once 'Scss/Node/Number.php';
48 require_once 'Scss/Formatter/OutputBlock.php';
53 * @author Leaf Corcoran <leafot@gmail.com>
57 const LINE_COMMENTS = 1;
62 const WITH_SUPPORTS = 4;
65 const SOURCE_MAP_NONE = 0;
66 const SOURCE_MAP_INLINE = 1;
67 const SOURCE_MAP_FILE = 2;
72 static protected $operatorNames = [
92 static protected $namespaces = [
98 static public $true = [HTML_Scss_Type::T_KEYWORD, 'true'];
99 static public $false = [HTML_Scss_Type::T_KEYWORD, 'false'];
100 static public $null = [HTML_Scss_Type::T_NULL];
101 static public $nullString = [HTML_Scss_Type::T_STRING, '', []];
102 static public $defaultValue = [HTML_Scss_Type::T_KEYWORD, ''];
103 static public $selfSelector = [HTML_Scss_Type::T_SELF];
104 static public $emptyList = [HTML_Scss_Type::T_LIST, '', []];
105 static public $emptyMap = [HTML_Scss_Type::T_MAP, [], []];
106 static public $emptyString = [HTML_Scss_Type::T_STRING, '"', []];
107 static public $with = [HTML_Scss_Type::T_KEYWORD, 'with'];
108 static public $without = [HTML_Scss_Type::T_KEYWORD, 'without'];
110 protected $importPaths = [''];
111 protected $importCache = [];
112 protected $importedFiles = [];
113 protected $userFunctions = [];
114 protected $registeredVars = [];
115 protected $registeredFeatures = [
116 'extend-selector-pseudoclass' => false,
118 'units-level-3' => false,
119 'global-variable-shadowing' => false,
122 protected $encoding = null;
123 protected $lineNumberStyle = null;
125 protected $sourceMap = self::SOURCE_MAP_NONE;
126 protected $sourceMapOptions = [];
129 * @var string|\Leafo\ScssPhp\Formatter
131 protected $formatter = 'Nested';
134 protected $rootBlock;
137 * @var \Leafo\ScssPhp\Compiler\Environment
142 protected $charsetSeen;
143 protected $sourceNames;
145 private $indentLevel;
146 private $commentsSeen;
149 private $parsedFiles;
151 private $sourceIndex;
153 private $sourceColumn;
155 private $shouldEvaluate;
156 private $ignoreErrors;
161 public function __construct()
163 $this->parsedFiles = [];
164 $this->sourceNames = [];
172 * @param string $code
173 * @param string $path
177 public function compile($code, $path = null)
179 $this->indentLevel = -1;
180 $this->commentsSeen = [];
182 $this->extendsMap = [];
183 $this->sourceIndex = null;
184 $this->sourceLine = null;
185 $this->sourceColumn = null;
188 $this->storeEnv = null;
189 $this->charsetSeen = null;
190 $this->shouldEvaluate = null;
191 $this->stderr = fopen('php://stderr', 'w');
193 $this->parser = $this->parserFactory($path);
194 $tree = $this->parser->parse($code);
196 $this->parser = null;
198 $formatter = 'HTML_Scss_Formatter_' . $this->formatter;
199 $fn = str_replace('_', '/', $formatter ) . '.php';
201 $this->formatter = new $formatter();
202 $this->rootBlock = null;
203 $this->rootEnv = $this->pushEnv($tree);
205 $this->injectVariables($this->registeredVars);
206 $this->compileRoot($tree);
209 $sourceMapGenerator = null;
211 if ($this->sourceMap) {
212 if (is_object($this->sourceMap) && $this->sourceMap instanceof HTML_Scss_SourceMap_SourceMapGenerator) {
213 $sourceMapGenerator = $this->sourceMap;
214 $this->sourceMap = self::SOURCE_MAP_FILE;
215 } elseif ($this->sourceMap !== self::SOURCE_MAP_NONE) {
216 require_once 'Scss/SourceMap/SourceMapGenerator.php';
217 $sourceMapGenerator = new HTML_Scss_SourceMap_SourceMapGenerator($this->sourceMapOptions);
221 $out = $this->formatter->format($this->scope, $sourceMapGenerator);
223 if (! empty($out) && $this->sourceMap && $this->sourceMap !== self::SOURCE_MAP_NONE) {
224 $sourceMap = $sourceMapGenerator->generateJson();
225 $sourceMapUrl = null;
227 switch ($this->sourceMap) {
228 case self::SOURCE_MAP_INLINE:
229 $sourceMapUrl = sprintf('data:application/json,%s', HTML_Scss_Util::encodeURIComponent($sourceMap));
232 case self::SOURCE_MAP_FILE:
233 $sourceMapUrl = $sourceMapGenerator->saveMap($sourceMap);
237 $out .= sprintf('/*# sourceMappingURL=%s */', $sourceMapUrl);
246 * @param string $path
248 * @return \Leafo\ScssPhp\Parser
250 protected function parserFactory($path)
252 $parser = new HTML_Scss_Parser($path, count($this->sourceNames), $this->encoding);
254 $this->sourceNames[] = $path;
255 $this->addParsedFile($path);
263 * @param array $target
264 * @param array $origin
268 protected function isSelfExtend($target, $origin)
270 foreach ($origin as $sel) {
271 if (in_array($target, $sel)) {
282 * @param array $target
283 * @param array $origin
284 * @param \stdClass $block
286 protected function pushExtends($target, $origin, $block)
288 if ($this->isSelfExtend($target, $origin)) {
292 $i = count($this->extends);
293 $this->extends[] = [$target, $origin, $block];
295 foreach ($target as $part) {
296 if (isset($this->extendsMap[$part])) {
297 $this->extendsMap[$part][] = $i;
299 $this->extendsMap[$part] = [$i];
307 * @param string $type
308 * @param array $selectors
310 * @return \Leafo\ScssPhp\Formatter\OutputBlock
312 protected function makeOutputBlock($type, $selectors = null)
315 $out = new HTML_Scss_Formatter_OutputBlock;
319 $out->parent = $this->scope;
320 $out->selectors = $selectors;
321 $out->depth = $this->env->depth;
323 if ($this->env->block instanceof HTML_Scss_Block) {
324 $out->sourceName = $this->env->block->sourceName;
325 $out->sourceLine = $this->env->block->sourceLine;
326 $out->sourceColumn = $this->env->block->sourceColumn;
328 $out->sourceName = null;
329 $out->sourceLine = null;
330 $out->sourceColumn = null;
339 * @param \Leafo\ScssPhp\Block $rootBlock
341 protected function compileRoot(HTML_Scss_Block $rootBlock)
343 $this->rootBlock = $this->scope = $this->makeOutputBlock(HTML_Scss_Type::T_ROOT);
345 $this->compileChildrenNoReturn($rootBlock->children, $this->scope);
346 $this->flattenSelectors($this->scope);
347 $this->missingSelectors();
351 * Report missing selectors
353 protected function missingSelectors()
355 foreach ($this->extends as $extend) {
356 if (isset($extend[3])) {
360 list($target, $origin, $block) = $extend;
362 // ignore if !optional
367 $target = implode(' ', $target);
368 $origin = $this->collapseSelectors($origin);
370 $this->sourceLine = $block[HTML_Scss_Parser::SOURCE_LINE];
371 $this->throwError("\"$origin\" failed to @extend \"$target\". The selector \"$target\" was not found.");
378 * @param \Leafo\ScssPhp\Formatter\OutputBlock $block
379 * @param string $parentKey
381 protected function flattenSelectors(HTML_Scss_Formatter_OutputBlock $block, $parentKey = null)
383 if ($block->selectors) {
386 foreach ($block->selectors as $s) {
389 if (! is_array($s)) {
394 if (! empty($this->extendsMap)) {
395 $this->matchExtends($s, $selectors);
398 array_walk($selectors, function (&$value) {
399 $value = serialize($value);
402 $selectors = array_unique($selectors);
404 array_walk($selectors, function (&$value) {
405 $value = unserialize($value);
410 $block->selectors = [];
411 $placeholderSelector = false;
413 foreach ($selectors as $selector) {
414 if ($this->hasSelectorPlaceholder($selector)) {
415 $placeholderSelector = true;
419 $block->selectors[] = $this->compileSelector($selector);
422 if ($placeholderSelector && 0 === count($block->selectors) && null !== $parentKey) {
423 unset($block->parent->children[$parentKey]);
429 foreach ($block->children as $key => $child) {
430 $this->flattenSelectors($child, $key);
437 * @param array $selector
439 * @param integer $from
440 * @param boolean $initial
442 protected function matchExtends($selector, &$out, $from = 0, $initial = true)
444 foreach ($selector as $i => $part) {
449 if ($this->matchExtendsSingle($part, $origin)) {
450 $after = array_slice($selector, $i + 1);
451 $before = array_slice($selector, 0, $i);
453 list($before, $nonBreakableBefore) = $this->extractRelationshipFromFragment($before);
455 foreach ($origin as $new) {
458 // remove shared parts
460 while ($k < $i && isset($new[$k]) && $selector[$k] === $new[$k]) {
466 $tempReplacement = $k > 0 ? array_slice($new, $k) : $new;
468 for ($l = count($tempReplacement) - 1; $l >= 0; $l--) {
469 $slice = $tempReplacement[$l];
470 array_unshift($replacement, $slice);
472 if (! $this->isImmediateRelationshipCombinator(end($slice))) {
477 $afterBefore = $l != 0 ? array_slice($tempReplacement, 0, $l) : [];
479 // Merge shared direct relationships.
480 $mergedBefore = $this->mergeDirectRelationships($afterBefore, $nonBreakableBefore);
482 $result = array_merge(
489 if ($result === $selector) {
495 // recursively check for more matches
496 $this->matchExtends($result, $out, count($before) + count($mergedBefore), false);
498 // selector sequence merging
499 if (! empty($before) && count($new) > 1) {
500 $sharedParts = $k > 0 ? array_slice($before, 0, $k) : [];
501 $postSharedParts = $k > 0 ? array_slice($before, $k) : $before;
503 list($injectBetweenSharedParts, $nonBreakable2) = $this->extractRelationshipFromFragment($afterBefore);
505 $result2 = array_merge(
507 $injectBetweenSharedParts,
523 * Match extends single
525 * @param array $rawSingle
526 * @param array $outOrigin
530 protected function matchExtendsSingle($rawSingle, &$outOrigin)
535 foreach ($rawSingle as $part) {
537 if (! is_string($part)) {
541 if (! preg_match('/^[\[.:#%]/', $part) && count($single)) {
542 $single[count($single) - 1] .= $part;
548 $extendingDecoratedTag = false;
550 if (count($single) > 1) {
552 $extendingDecoratedTag = preg_match('/^[a-z0-9]+$/i', $single[0], $matches) ? $matches[0] : false;
555 foreach ($single as $part) {
556 if (isset($this->extendsMap[$part])) {
557 foreach ($this->extendsMap[$part] as $idx) {
558 $counts[$idx] = isset($counts[$idx]) ? $counts[$idx] + 1 : 1;
566 foreach ($counts as $idx => $count) {
567 list($target, $origin, /* $block */) = $this->extends[$idx];
570 if ($count !== count($target)) {
574 $this->extends[$idx][3] = true;
576 $rem = array_diff($single, $target);
578 foreach ($origin as $j => $new) {
579 // prevent infinite loop when target extends itself
580 if ($this->isSelfExtend($single, $origin)) {
584 $replacement = end($new);
586 // Extending a decorated tag with another tag is not possible.
587 if ($extendingDecoratedTag && $replacement[0] != $extendingDecoratedTag &&
588 preg_match('/^[a-z0-9]+$/i', $replacement[0])
594 $combined = $this->combineSelectorSingle($replacement, $rem);
596 if (count(array_diff($combined, $origin[$j][count($origin[$j]) - 1]))) {
597 $origin[$j][count($origin[$j]) - 1] = $combined;
601 $outOrigin = array_merge($outOrigin, $origin);
611 * Extract a relationship from the fragment.
613 * When extracting the last portion of a selector we will be left with a
614 * fragment which may end with a direction relationship combinator. This
615 * method will extract the relationship fragment and return it along side
618 * @param array $fragment The selector fragment maybe ending with a direction relationship combinator.
619 * @return array The selector without the relationship fragment if any, the relationship fragment.
621 protected function extractRelationshipFromFragment(array $fragment)
625 $j = $i = count($fragment);
628 $children = $j != $i ? array_slice($fragment, $j, $i - $j) : [];
629 $parents = array_slice($fragment, 0, $j);
630 $slice = end($parents);
632 if (empty($slice) || ! $this->isImmediateRelationshipCombinator($slice[0])) {
639 return [$parents, $children];
643 * Combine selector single
646 * @param array $other
650 protected function combineSelectorSingle($base, $other)
656 foreach ([$base, $other] as $single) {
657 foreach ($single as $part) {
658 if (preg_match('/^[\[.:#]/', $part)) {
661 } elseif (preg_match('/^[^_-]/', $part)) {
665 $tag[count($tag) - 1] .= $part;
667 $out[count($out) - 1] .= $part;
673 array_unshift($out, $tag[0]);
682 * @param \Leafo\ScssPhp\Block $media
684 protected function compileMedia(HTML_Scss_Block $media)
686 $this->pushEnv($media);
688 $mediaQuery = $this->compileMediaQuery($this->multiplyMedia($this->env));
690 if (! empty($mediaQuery)) {
691 $this->scope = $this->makeOutputBlock(HTML_Scss_Type::T_MEDIA, [$mediaQuery]);
693 $parentScope = $this->mediaParent($this->scope);
694 $parentScope->children[] = $this->scope;
696 // top level properties in a media cause it to be wrapped
699 foreach ($media->children as $child) {
702 if ($type !== HTML_Scss_Type::T_BLOCK &&
703 $type !== HTML_Scss_Type::T_MEDIA &&
704 $type !== HTML_Scss_Type::T_DIRECTIVE &&
705 $type !== HTML_Scss_Type::T_IMPORT
713 $wrapped = new HTML_Scss_Block;
714 $wrapped->sourceName = $media->sourceName;
715 $wrapped->sourceIndex = $media->sourceIndex;
716 $wrapped->sourceLine = $media->sourceLine;
717 $wrapped->sourceColumn = $media->sourceColumn;
718 $wrapped->selectors = [];
719 $wrapped->comments = [];
720 $wrapped->parent = $media;
721 $wrapped->children = $media->children;
723 $media->children = [[HTML_Scss_Type::T_BLOCK, $wrapped]];
726 $this->compileChildrenNoReturn($media->children, $this->scope);
728 $this->scope = $this->scope->parent;
737 * @param \Leafo\ScssPhp\Formatter\OutputBlock $scope
739 * @return \Leafo\ScssPhp\Formatter\OutputBlock
741 protected function mediaParent(HTML_Scss_Formatter_OutputBlock $scope)
743 while (! empty($scope->parent)) {
744 if (! empty($scope->type) && $scope->type !== HTML_Scss_Type::T_MEDIA) {
748 $scope = $scope->parent;
757 * @param \Leafo\ScssPhp\Block $block
759 protected function compileDirective(HTML_Scss_Block $block)
761 $s = '@' . $block->name;
763 if (! empty($block->value)) {
764 $s .= ' ' . $this->compileValue($block->value);
767 if ($block->name === 'keyframes' || substr($block->name, -10) === '-keyframes') {
768 $this->compileKeyframeBlock($block, [$s]);
770 $this->compileNestedBlock($block, [$s]);
777 * @param \Leafo\ScssPhp\Block $block
779 protected function compileAtRoot(HTML_Scss_Block $block)
781 $env = $this->pushEnv($block);
782 $envs = $this->compactEnv($env);
783 $without = isset($block->with) ? $this->compileWith($block->with) : static::WITH_RULE;
785 // wrap inline selector
786 if ($block->selector) {
787 $wrapped = new HTML_Scss_Block;
788 $wrapped->sourceName = $block->sourceName;
789 $wrapped->sourceIndex = $block->sourceIndex;
790 $wrapped->sourceLine = $block->sourceLine;
791 $wrapped->sourceColumn = $block->sourceColumn;
792 $wrapped->selectors = $block->selector;
793 $wrapped->comments = [];
794 $wrapped->parent = $block;
795 $wrapped->children = $block->children;
797 $block->children = [[HTML_Scss_Type::T_BLOCK, $wrapped]];
800 $this->env = $this->filterWithout($envs, $without);
801 $newBlock = $this->spliceTree($envs, $block, $without);
803 $saveScope = $this->scope;
804 $this->scope = $this->rootBlock;
806 $this->compileChild($newBlock, $this->scope);
808 $this->scope = $saveScope;
809 $this->env = $this->extractEnv($envs);
818 * @param \Leafo\ScssPhp\Block $block
819 * @param integer $without
823 private function spliceTree($envs, HTML_Scss_Block $block, $without)
827 foreach ($envs as $e) {
828 if (! isset($e->block)) {
832 if ($e->block === $block) {
836 if (isset($e->block->type) && $e->block->type === HTML_Scss_Type::T_AT_ROOT) {
840 if ($e->block && $this->isWithout($without, $e->block)) {
844 $b = new HTML_Scss_Block;
845 $b->sourceName = $e->block->sourceName;
846 $b->sourceIndex = $e->block->sourceIndex;
847 $b->sourceLine = $e->block->sourceLine;
848 $b->sourceColumn = $e->block->sourceColumn;
850 $b->comments = $e->block->comments;
854 $type = isset($newBlock->type) ? $newBlock->type : HTML_Scss_Type::T_BLOCK;
856 $b->children = [[$type, $newBlock]];
858 $newBlock->parent = $b;
859 } elseif (count($block->children)) {
860 foreach ($block->children as $child) {
861 if ($child[0] === HTML_Scss_Type::T_BLOCK) {
862 $child[1]->parent = $b;
866 $b->children = $block->children;
869 if (isset($e->block->type)) {
870 $b->type = $e->block->type;
873 if (isset($e->block->name)) {
874 $b->name = $e->block->name;
877 if (isset($e->block->queryList)) {
878 $b->queryList = $e->block->queryList;
881 if (isset($e->block->value)) {
882 $b->value = $e->block->value;
888 $type = isset($newBlock->type) ? $newBlock->type : HTML_Scss_Type::T_BLOCK;
890 return [$type, $newBlock];
894 * Compile @at-root's with: inclusion / without: exclusion into filter flags
900 private function compileWith($with)
903 'rule' => self::WITH_RULE,
904 'media' => self::WITH_MEDIA,
905 'supports' => self::WITH_SUPPORTS,
906 'all' => self::WITH_ALL,
909 // exclude selectors by default
910 $without = static::WITH_RULE;
912 if ($this->libMapHasKey([$with, static::$with])) {
913 $without = static::WITH_ALL;
915 $list = $this->coerceList($this->libMapGet([$with, static::$with]));
917 foreach ($list[2] as $item) {
918 $keyword = $this->compileStringContent($this->coerceString($item));
920 if (array_key_exists($keyword, $mapping)) {
921 $without &= ~($mapping[$keyword]);
926 if ($this->libMapHasKey([$with, static::$without])) {
929 $list = $this->coerceList($this->libMapGet([$with, static::$without]));
931 foreach ($list[2] as $item) {
932 $keyword = $this->compileStringContent($this->coerceString($item));
934 if (array_key_exists($keyword, $mapping)) {
935 $without |= $mapping[$keyword];
947 * @param integer $without
949 * @return \Leafo\ScssPhp\Compiler\Environment
951 private function filterWithout($envs, $without)
955 foreach ($envs as $e) {
956 if ($e->block && $this->isWithout($without, $e->block)) {
963 return $this->extractEnv($filtered);
969 * @param integer $without
970 * @param \Leafo\ScssPhp\Block $block
974 private function isWithout($without, HTML_Scss_Block $block)
976 if ((($without & static::WITH_RULE) && isset($block->selectors)) ||
977 (($without & static::WITH_MEDIA) &&
978 isset($block->type) && $block->type === HTML_Scss_Type::T_MEDIA) ||
979 (($without & static::WITH_SUPPORTS) &&
980 isset($block->type) && $block->type === HTML_Scss_Type::T_DIRECTIVE &&
981 isset($block->name) && $block->name === 'supports')
990 * Compile keyframe block
992 * @param \Leafo\ScssPhp\Block $block
993 * @param array $selectors
995 protected function compileKeyframeBlock(HTML_Scss_Block $block, $selectors)
997 $env = $this->pushEnv($block);
999 $envs = $this->compactEnv($env);
1001 $this->env = $this->extractEnv(array_filter($envs, function (HTML_Scss_Compiler_Environment $e) {
1002 return ! isset($e->block->selectors);
1005 $this->scope = $this->makeOutputBlock($block->type, $selectors);
1006 $this->scope->depth = 1;
1007 $this->scope->parent->children[] = $this->scope;
1009 $this->compileChildrenNoReturn($block->children, $this->scope);
1011 $this->scope = $this->scope->parent;
1012 $this->env = $this->extractEnv($envs);
1018 * Compile nested block
1020 * @param \Leafo\ScssPhp\Block $block
1021 * @param array $selectors
1023 protected function compileNestedBlock(HTML_Scss_Block $block, $selectors)
1025 $this->pushEnv($block);
1027 $this->scope = $this->makeOutputBlock($block->type, $selectors);
1028 $this->scope->parent->children[] = $this->scope;
1030 $this->compileChildrenNoReturn($block->children, $this->scope);
1032 $this->scope = $this->scope->parent;
1038 * Recursively compiles a block.
1040 * A block is analogous to a CSS block in most cases. A single SCSS document
1041 * is encapsulated in a block when parsed, but it does not have parent tags
1042 * so all of its children appear on the root level when compiled.
1044 * Blocks are made up of selectors and children.
1046 * The children of a block are just all the blocks that are defined within.
1048 * Compiling the block involves pushing a fresh environment on the stack,
1049 * and iterating through the props, compiling each one.
1051 * @see Compiler::compileChild()
1053 * @param \Leafo\ScssPhp\Block $block
1055 protected function compileBlock(HTML_Scss_Block $block)
1057 $env = $this->pushEnv($block);
1058 $env->selectors = $this->evalSelectors($block->selectors);
1060 $out = $this->makeOutputBlock(null);
1062 if (isset($this->lineNumberStyle) && count($env->selectors) && count($block->children)) {
1063 $annotation = $this->makeOutputBlock(HTML_Scss_Type::T_COMMENT);
1064 $annotation->depth = 0;
1066 $file = $this->sourceNames[$block->sourceIndex];
1067 $line = $block->sourceLine;
1069 switch ($this->lineNumberStyle) {
1070 case static::LINE_COMMENTS:
1071 $annotation->lines[] = '/* line ' . $line
1072 . ($file ? ', ' . $file : '')
1076 case static::DEBUG_INFO:
1077 $annotation->lines[] = '@media -sass-debug-info{'
1078 . ($file ? 'filename{font-family:"' . $file . '"}' : '')
1079 . 'line{font-family:' . $line . '}}';
1083 $this->scope->children[] = $annotation;
1086 $this->scope->children[] = $out;
1088 if (count($block->children)) {
1089 $out->selectors = $this->multiplySelectors($env);
1091 $this->compileChildrenNoReturn($block->children, $out);
1094 $this->formatter->stripSemicolon($out->lines);
1100 * Compile root level comment
1102 * @param array $block
1104 protected function compileComment($block)
1106 $out = $this->makeOutputBlock(HTML_Scss_Type::T_COMMENT);
1107 $out->lines[] = $block[1];
1108 $this->scope->children[] = $out;
1112 * Evaluate selectors
1114 * @param array $selectors
1118 protected function evalSelectors($selectors)
1120 $this->shouldEvaluate = false;
1122 $selectors = array_map([$this, 'evalSelector'], $selectors);
1124 // after evaluating interpolates, we might need a second pass
1125 if ($this->shouldEvaluate) {
1126 $buffer = $this->collapseSelectors($selectors);
1127 $parser = $this->parserFactory(__METHOD__);
1129 if ($parser->parseSelector($buffer, $newSelectors)) {
1130 $selectors = array_map([$this, 'evalSelector'], $newSelectors);
1140 * @param array $selector
1144 protected function evalSelector($selector)
1146 return array_map([$this, 'evalSelectorPart'], $selector);
1150 * Evaluate selector part; replaces all the interpolates, stripping quotes
1152 * @param array $part
1156 protected function evalSelectorPart($part)
1158 foreach ($part as &$p) {
1159 if (is_array($p) && ($p[0] === HTML_Scss_Type::T_INTERPOLATE || $p[0] === HTML_Scss_Type::T_STRING)) {
1160 $p = $this->compileValue($p);
1162 // force re-evaluation
1163 if (strpos($p, '&') !== false || strpos($p, ',') !== false) {
1164 $this->shouldEvaluate = true;
1166 } elseif (is_string($p) && strlen($p) >= 2 &&
1167 ($first = $p[0]) && ($first === '"' || $first === "'") &&
1168 substr($p, -1) === $first
1170 $p = substr($p, 1, -1);
1174 return $this->flattenSelectorSingle($part);
1178 * Collapse selectors
1180 * @param array $selectors
1184 protected function collapseSelectors($selectors)
1188 foreach ($selectors as $selector) {
1191 array_walk_recursive(
1193 function ($value, $key) use (&$output) {
1201 return implode(', ', $parts);
1205 * Flatten selector single; joins together .classes and #ids
1207 * @param array $single
1211 protected function flattenSelectorSingle($single)
1215 foreach ($single as $part) {
1216 if (empty($joined) ||
1217 ! is_string($part) ||
1218 preg_match('/[\[.:#%]/', $part)
1224 if (is_array(end($joined))) {
1227 $joined[count($joined) - 1] .= $part;
1235 * Compile selector to string; self(&) should have been replaced by now
1237 * @param string|array $selector
1241 protected function compileSelector($selector)
1243 if (! is_array($selector)) {
1244 return $selector; // media and the like
1250 [$this, 'compileSelectorPart'],
1257 * Compile selector part
1259 * @param array $piece
1263 protected function compileSelectorPart($piece)
1265 foreach ($piece as &$p) {
1266 if (! is_array($p)) {
1271 case HTML_Scss_Type::T_SELF:
1276 $p = $this->compileValue($p);
1281 return implode($piece);
1285 * Has selector placeholder?
1287 * @param array $selector
1291 protected function hasSelectorPlaceholder($selector)
1293 if (! is_array($selector)) {
1297 foreach ($selector as $parts) {
1298 foreach ($parts as $part) {
1299 if (strlen($part) && '%' === $part[0]) {
1309 * Compile children and return result
1311 * @param array $stms
1312 * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
1316 protected function compileChildren($stms, HTML_Scss_Formatter_OutputBlock $out)
1318 foreach ($stms as $stm) {
1319 $ret = $this->compileChild($stm, $out);
1328 * Compile children and throw exception if unexpected @return
1330 * @param array $stms
1331 * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
1333 * @throws \Exception
1335 protected function compileChildrenNoReturn($stms, HTML_Scss_Formatter_OutputBlock $out)
1337 foreach ($stms as $stm) {
1338 $ret = $this->compileChild($stm, $out);
1341 $this->throwError('@return may only be used within a function');
1349 * Compile media query
1351 * @param array $queryList
1355 protected function compileMediaQuery($queryList)
1360 foreach ($queryList as $query) {
1364 foreach ($query as $q) {
1366 case HTML_Scss_Type::T_MEDIA_TYPE:
1368 $type = $this->mergeMediaTypes(
1370 array_map([$this, 'compileValue'], array_slice($q, 1))
1373 if (empty($type)) { // merge failed
1377 $type = array_map([$this, 'compileValue'], array_slice($q, 1));
1381 case HTML_Scss_Type::T_MEDIA_EXPRESSION:
1384 . $this->compileValue($q[1])
1385 . $this->formatter->assignSeparator
1386 . $this->compileValue($q[2])
1390 . $this->compileValue($q[1])
1395 case HTML_Scss_Type::T_MEDIA_VALUE:
1396 $parts[] = $this->compileValue($q[1]);
1402 array_unshift($parts, implode(' ', array_filter($type)));
1405 if (! empty($parts)) {
1410 $out .= $this->formatter->tagSeparator;
1413 $out .= implode(' and ', $parts);
1420 protected function mergeDirectRelationships($selectors1, $selectors2)
1422 if (empty($selectors1) || empty($selectors2)) {
1423 return array_merge($selectors1, $selectors2);
1426 $part1 = end($selectors1);
1427 $part2 = end($selectors2);
1429 if (! $this->isImmediateRelationshipCombinator($part1[0]) || $part1 !== $part2) {
1430 return array_merge($selectors1, $selectors2);
1436 $part1 = array_pop($selectors1);
1437 $part2 = array_pop($selectors2);
1439 if ($this->isImmediateRelationshipCombinator($part1[0]) && $part1 !== $part2) {
1440 $merged = array_merge($selectors1, [$part1], $selectors2, [$part2], $merged);
1444 array_unshift($merged, $part1);
1445 array_unshift($merged, [array_pop($selectors1)[0] . array_pop($selectors2)[0]]);
1446 } while (! empty($selectors1) && ! empty($selectors2));
1454 * @param array $type1
1455 * @param array $type2
1457 * @return array|null
1459 protected function mergeMediaTypes($type1, $type2)
1461 if (empty($type1)) {
1465 if (empty($type2)) {
1472 if (count($type1) > 1) {
1473 $m1= strtolower($type1[0]);
1474 $t1= strtolower($type1[1]);
1476 $t1 = strtolower($type1[0]);
1482 if (count($type2) > 1) {
1483 $m2 = strtolower($type2[0]);
1484 $t2 = strtolower($type2[1]);
1486 $t2 = strtolower($type2[0]);
1489 if (($m1 === HTML_Scss_Type::T_NOT) ^ ($m2 === HTML_Scss_Type::T_NOT)) {
1495 $m1 === HTML_Scss_Type::T_NOT ? $m2 : $m1,
1496 $m1 === HTML_Scss_Type::T_NOT ? $t2 : $t1,
1500 if ($m1 === HTML_Scss_Type::T_NOT && $m2 === HTML_Scss_Type::T_NOT) {
1501 // CSS has no way of representing "neither screen nor print"
1506 return [HTML_Scss_Type::T_NOT, $t1];
1513 // t1 == t2, neither m1 nor m2 are "not"
1514 return [empty($m1)? $m2 : $m1, $t1];
1518 * Compile import; returns true if the value was something that could be imported
1520 * @param array $rawPath
1522 * @param boolean $once
1526 protected function compileImport($rawPath, $out, $once = false)
1529 if ($rawPath[0] === HTML_Scss_Type::T_STRING) {
1530 //print_R($rawPath);
1531 $path = $this->compileStringContent($rawPath);
1533 if ($npath = $this->findImport($path)) {
1534 if (! $once || ! in_array($npath, $this->importedFiles)) {
1535 $this->importFile($npath, $out);
1536 $this->importedFiles[] = $npath;
1541 die("could not find @import : " . $path ."\n");
1546 if ($rawPath[0] === HTML_Scss_Type::T_LIST) {
1547 // handle a list of strings
1548 if (count($rawPath[2]) === 0) {
1552 foreach ($rawPath[2] as $path) {
1553 if ($path[0] !== HTML_Scss_Type::T_STRING) {
1558 foreach ($rawPath[2] as $path) {
1559 $this->compileImport($path, $out);
1569 * Compile child; returns a value to halt execution
1571 * @param array $child
1572 * @param \Leafo\ScssPhp\Formatter\OutputBlock $out
1576 protected function compileChild($child, HTML_Scss_Formatter_OutputBlock $out)
1578 $this->sourceIndex = isset($child[HTML_Scss_Parser::SOURCE_INDEX]) ? $child[HTML_Scss_Parser::SOURCE_INDEX] : null;
1579 $this->sourceLine = isset($child[HTML_Scss_Parser::SOURCE_LINE]) ? $child[HTML_Scss_Parser::SOURCE_LINE] : -1;
1580 $this->sourceColumn = isset($child[HTML_Scss_Parser::SOURCE_COLUMN]) ? $child[HTML_Scss_Parser::SOURCE_COLUMN] : -1;
1582 switch ($child[0]) {
1583 case HTML_Scss_Type::T_SCSSPHP_IMPORT_ONCE:
1584 list(, $rawPath) = $child;
1586 $rawPath = $this->reduce($rawPath);
1588 if (! $this->compileImport($rawPath, $out, true)) {
1589 $out->lines[] = '@import ' . $this->compileValue($rawPath) . ';';
1593 case HTML_Scss_Type::T_IMPORT:
1594 list(, $rawPath) = $child;
1595 //echo "import:"; print_r($child);
1596 $rawPath = $this->reduce($rawPath);
1597 //echo "rawpath:"; print_r($rawPath);
1598 if (! $this->compileImport($rawPath, $out)) {
1599 $out->lines[] = '@import ' . $this->compileValue($rawPath) . ';';
1603 case HTML_Scss_Type::T_DIRECTIVE:
1604 $this->compileDirective($child[1]);
1607 case HTML_Scss_Type::T_AT_ROOT:
1608 $this->compileAtRoot($child[1]);
1611 case HTML_Scss_Type::T_MEDIA:
1612 $this->compileMedia($child[1]);
1615 case HTML_Scss_Type::T_BLOCK:
1616 $this->compileBlock($child[1]);
1619 case HTML_Scss_Type::T_CHARSET:
1620 if (! $this->charsetSeen) {
1621 $this->charsetSeen = true;
1623 $out->lines[] = '@charset ' . $this->compileValue($child[1]) . ';';
1627 case HTML_Scss_Type::T_ASSIGN:
1628 list(, $name, $value) = $child;
1630 if ($name[0] === HTML_Scss_Type::T_VARIABLE) {
1631 $flags = isset($child[3]) ? $child[3] : [];
1632 $isDefault = in_array('!default', $flags);
1633 $isGlobal = in_array('!global', $flags);
1636 $this->set($name[1], $this->reduce($value), false, $this->rootEnv);
1640 $shouldSet = $isDefault &&
1641 (($result = $this->get($name[1], false)) === null
1642 || $result === static::$null);
1644 if (! $isDefault || $shouldSet) {
1645 $this->set($name[1], $this->reduce($value));
1650 $compiledName = $this->compileValue($name);
1652 // handle shorthand syntax: size / line-height
1653 if ($compiledName === 'font') {
1654 if ($value[0] === HTML_Scss_Type::T_EXPRESSION && $value[1] === '/') {
1655 $value = $this->expToString($value);
1656 } elseif ($value[0] === HTML_Scss_Type::T_LIST) {
1657 foreach ($value[2] as &$item) {
1658 if ($item[0] === HTML_Scss_Type::T_EXPRESSION && $item[1] === '/') {
1659 $item = $this->expToString($item);
1665 // if the value reduces to null from something else then
1666 // the property should be discarded
1667 if ($value[0] !== HTML_Scss_Type::T_NULL) {
1668 $value = $this->reduce($value);
1670 if ($value[0] === HTML_Scss_Type::T_NULL || $value === static::$nullString) {
1675 $compiledValue = $this->compileValue($value);
1677 $out->lines[] = $this->formatter->property(
1683 case HTML_Scss_Type::T_COMMENT:
1684 if ($out->type === HTML_Scss_Type::T_ROOT) {
1685 $this->compileComment($child);
1689 $out->lines[] = $child[1];
1692 case HTML_Scss_Type::T_MIXIN:
1693 case HTML_Scss_Type::T_FUNCTION:
1694 list(, $block) = $child;
1696 $this->set(static::$namespaces[$block->type] . $block->name, $block);
1699 case HTML_Scss_Type::T_EXTEND:
1700 list(, $selectors) = $child;
1702 foreach ($selectors as $sel) {
1703 $results = $this->evalSelectors([$sel]);
1705 foreach ($results as $result) {
1706 // only use the first one
1707 $result = current($result);
1709 $this->pushExtends($result, $out->selectors, $child);
1714 case HTML_Scss_Type::T_IF:
1715 list(, $if) = $child;
1717 if ($this->isTruthy($this->reduce($if->cond, true))) {
1718 return $this->compileChildren($if->children, $out);
1721 foreach ($if->cases as $case) {
1722 if ($case->type === HTML_Scss_Type::T_ELSE ||
1723 $case->type === HTML_Scss_Type::T_ELSEIF && $this->isTruthy($this->reduce($case->cond))
1725 return $this->compileChildren($case->children, $out);
1730 case HTML_Scss_Type::T_EACH:
1731 list(, $each) = $child;
1733 $list = $this->coerceList($this->reduce($each->list));
1737 foreach ($list[2] as $item) {
1738 if (count($each->vars) === 1) {
1739 $this->set($each->vars[0], $item, true);
1741 list(,, $values) = $this->coerceList($item);
1743 foreach ($each->vars as $i => $var) {
1744 $this->set($var, isset($values[$i]) ? $values[$i] : static::$null, true);
1748 $ret = $this->compileChildren($each->children, $out);
1751 if ($ret[0] !== HTML_Scss_Type::T_CONTROL) {
1766 case HTML_Scss_Type::T_WHILE:
1767 list(, $while) = $child;
1769 while ($this->isTruthy($this->reduce($while->cond, true))) {
1770 $ret = $this->compileChildren($while->children, $out);
1773 if ($ret[0] !== HTML_Scss_Type::T_CONTROL) {
1784 case HTML_Scss_Type::T_FOR:
1785 list(, $for) = $child;
1787 $start = $this->reduce($for->start, true);
1788 $end = $this->reduce($for->end, true);
1790 if (! ($start[2] == $end[2] || $end->unitless())) {
1791 $this->throwError('Incompatible units: "%s" and "%s".', $start->unitStr(), $end->unitStr());
1800 $d = $start < $end ? 1 : -1;
1804 if ((! $for->until && $start - $d == $end) ||
1805 ($for->until && $start == $end)
1810 $this->set($for->var, new HTML_Scss_Node_Number($start, $unit));
1813 $ret = $this->compileChildren($for->children, $out);
1816 if ($ret[0] !== HTML_Scss_Type::T_CONTROL) {
1827 case HTML_Scss_Type::T_BREAK:
1828 return [HTML_Scss_Type::T_CONTROL, true];
1830 case HTML_Scss_Type::T_CONTINUE:
1831 return [HTML_Scss_Type::T_CONTROL, false];
1833 case HTML_Scss_Type::T_RETURN:
1834 return $this->reduce($child[1], true);
1836 case HTML_Scss_Type::T_NESTED_PROPERTY:
1837 list(, $prop) = $child;
1840 $prefix = $this->compileValue($prop->prefix) . '-';
1842 foreach ($prop->children as $child) {
1843 switch ($child[0]) {
1844 case HTML_Scss_Type::T_ASSIGN:
1845 array_unshift($child[1][2], $prefix);
1848 case HTML_Scss_Type::T_NESTED_PROPERTY:
1849 array_unshift($child[1]->prefix[2], $prefix);
1853 $prefixed[] = $child;
1856 $this->compileChildrenNoReturn($prefixed, $out);
1859 case HTML_Scss_Type::T_INCLUDE:
1860 // including a mixin
1861 list(, $name, $argValues, $content) = $child;
1863 $mixin = $this->get(static::$namespaces['mixin'] . $name, false);
1866 $this->throwError("Undefined mixin $name");
1870 $callingScope = $this->getStoreEnv();
1872 // push scope, apply args
1874 $this->env->depth--;
1876 $storeEnv = $this->storeEnv;
1877 $this->storeEnv = $this->env;
1879 if (isset($content)) {
1880 $content->scope = $callingScope;
1882 $this->setRaw(static::$namespaces['special'] . 'content', $content, $this->env);
1885 if (isset($mixin->args)) {
1886 $this->applyArguments($mixin->args, $argValues);
1889 $this->env->marker = 'mixin';
1891 $this->compileChildrenNoReturn($mixin->children, $out);
1893 $this->storeEnv = $storeEnv;
1898 case HTML_Scss_Type::T_MIXIN_CONTENT:
1899 $content = $this->get(static::$namespaces['special'] . 'content', false, $this->getStoreEnv())
1900 ?: $this->get(static::$namespaces['special'] . 'content', false, $this->env);
1903 $content = new StdClass();
1904 $content->scope = new StdClass();
1905 $content->children = $this->storeEnv->parent->block->children;
1909 $storeEnv = $this->storeEnv;
1910 $this->storeEnv = $content->scope;
1912 $this->compileChildrenNoReturn($content->children, $out);
1914 $this->storeEnv = $storeEnv;
1917 case HTML_Scss_Type::T_DEBUG:
1918 list(, $value) = $child;
1920 $line = $this->sourceLine;
1921 $value = $this->compileValue($this->reduce($value, true));
1922 fwrite($this->stderr, "Line $line DEBUG: $value\n");
1925 case HTML_Scss_Type::T_WARN:
1926 list(, $value) = $child;
1928 $line = $this->sourceLine;
1929 $value = $this->compileValue($this->reduce($value, true));
1930 fwrite($this->stderr, "Line $line WARN: $value\n");
1933 case HTML_Scss_Type::T_ERROR:
1934 list(, $value) = $child;
1936 $line = $this->sourceLine;
1937 $value = $this->compileValue($this->reduce($value, true));
1938 $this->throwError("Line $line ERROR: $value\n");
1941 case HTML_Scss_Type::T_CONTROL:
1942 $this->throwError('@break/@continue not permitted in this scope');
1946 $this->throwError("unknown child type: $child[0]");
1951 * Reduce expression to string
1957 protected function expToString($exp)
1959 list(, $op, $left, $right, /* $inParens */, $whiteLeft, $whiteRight) = $exp;
1961 $content = [$this->reduce($left)];
1973 $content[] = $this->reduce($right);
1975 return [HTML_Scss_Type::T_STRING, '', $content];
1981 * @param array $value
1985 protected function isTruthy($value)
1987 return $value !== static::$false && $value !== static::$null;
1991 * Is the value a direct relationship combinator?
1993 * @param string $value
1997 protected function isImmediateRelationshipCombinator($value)
1999 return $value === '>' || $value === '+' || $value === '~';
2003 * Should $value cause its operand to eval
2005 * @param array $value
2009 protected function shouldEval($value)
2011 switch ($value[0]) {
2012 case HTML_Scss_Type::T_EXPRESSION:
2013 if ($value[1] === '/') {
2014 return $this->shouldEval($value[2], $value[3]);
2018 case HTML_Scss_Type::T_VARIABLE:
2019 case HTML_Scss_Type::T_FUNCTION_CALL:
2029 * @param array $value
2030 * @param boolean $inExp
2032 * @return array|\Leafo\ScssPhp\Node\Number
2034 protected function reduce($value, $inExp = false)
2036 list($type) = $value;
2039 case HTML_Scss_Type::T_EXPRESSION:
2040 list(, $op, $left, $right, $inParens) = $value;
2042 $opName = isset(static::$operatorNames[$op]) ? static::$operatorNames[$op] : $op;
2043 $inExp = $inExp || $this->shouldEval($left) || $this->shouldEval($right);
2045 $left = $this->reduce($left, true);
2047 if ($op !== 'and' && $op !== 'or') {
2048 $right = $this->reduce($right, true);
2051 // special case: looks like css shorthand
2052 if ($opName == 'div' && ! $inParens && ! $inExp && isset($right[2])
2053 && (($right[0] !== HTML_Scss_Type::T_NUMBER && $right[2] != '')
2054 || ($right[0] === HTML_Scss_Type::T_NUMBER && ! $right->unitless()))
2056 return $this->expToString($value);
2059 $left = $this->coerceForExpression($left);
2060 $right = $this->coerceForExpression($right);
2065 $ucOpName = ucfirst($opName);
2066 $ucLType = ucfirst($ltype);
2067 $ucRType = ucfirst($rtype);
2070 // 1. op[op name][left type][right type]
2071 // 2. op[left type][right type] (passing the op as first arg
2073 $fn = "op${ucOpName}${ucLType}${ucRType}";
2075 if (is_callable([$this, $fn]) ||
2076 (($fn = "op${ucLType}${ucRType}") &&
2077 is_callable([$this, $fn]) &&
2079 (($fn = "op${ucOpName}") &&
2080 is_callable([$this, $fn]) &&
2083 $coerceUnit = false;
2085 if (! isset($genOp) &&
2086 $left[0] === HTML_Scss_Type::T_NUMBER && $right[0] === HTML_Scss_Type::T_NUMBER
2092 $targetUnit = $left[2];
2094 foreach ($right[2] as $unit => $exp) {
2095 $targetUnit[$unit] = (isset($targetUnit[$unit]) ? $targetUnit[$unit] : 0) + $exp;
2100 $targetUnit = $left[2];
2102 foreach ($right[2] as $unit => $exp) {
2103 $targetUnit[$unit] = (isset($targetUnit[$unit]) ? $targetUnit[$unit] : 0) - $exp;
2108 $targetUnit = $left[2];
2112 $targetUnit = $left->unitless() ? $right[2] : $left[2];
2115 if (! $left->unitless() && ! $right->unitless()) {
2116 $left = $left->normalize();
2117 $right = $right->normalize();
2121 $shouldEval = $inParens || $inExp;
2123 if (isset($passOp)) {
2124 $out = $this->$fn($op, $left, $right, $shouldEval);
2126 $out = $this->$fn($left, $right, $shouldEval);
2130 if ($coerceUnit && $out[0] === HTML_Scss_Type::T_NUMBER) {
2131 $out = $out->coerce($targetUnit);
2138 return $this->expToString($value);
2140 case HTML_Scss_Type::T_UNARY:
2141 list(, $op, $exp, $inParens) = $value;
2143 $inExp = $inExp || $this->shouldEval($exp);
2144 $exp = $this->reduce($exp);
2146 if ($exp[0] === HTML_Scss_Type::T_NUMBER) {
2151 return new HTML_Scss_Node_Number($exp[1], $exp[2]);
2154 return new HTML_Scss_Node_Number(-$exp[1], $exp[2]);
2158 if ($op === 'not') {
2159 if ($inExp || $inParens) {
2160 if ($exp === static::$false || $exp === static::$null) {
2161 return static::$true;
2164 return static::$false;
2170 return [HTML_Scss_Type::T_STRING, '', [$op, $exp]];
2172 case HTML_Scss_Type::T_VARIABLE:
2173 list(, $name) = $value;
2175 return $this->reduce($this->get($name));
2177 case HTML_Scss_Type::T_LIST:
2178 foreach ($value[2] as &$item) {
2179 $item = $this->reduce($item);
2184 case HTML_Scss_Type::T_MAP:
2185 foreach ($value[1] as &$item) {
2186 $item = $this->reduce($item);
2189 foreach ($value[2] as &$item) {
2190 $item = $this->reduce($item);
2195 case HTML_Scss_Type::T_STRING:
2196 foreach ($value[2] as &$item) {
2197 if (is_array($item) || $item instanceof ArrayAccess) {
2198 $item = $this->reduce($item);
2203 case HTML_Scss_Type::T_INTERPOLATE:
2204 $value[1] = $this->reduce($value[1]);
2208 case HTML_Scss_Type::T_FUNCTION_CALL:
2209 list(, $name, $argValues) = $value;
2211 return $this->fncall($name, $argValues);
2221 * @param string $name
2222 * @param array $argValues
2224 * @return array|null
2226 private function fncall($name, $argValues)
2229 if ($this->callScssFunction($name, $argValues, $returnValue)) {
2230 return $returnValue;
2233 // native PHP functions
2234 if ($this->callNativeFunction($name, $argValues, $returnValue)) {
2235 return $returnValue;
2238 // for CSS functions, simply flatten the arguments into a list
2241 foreach ((array) $argValues as $arg) {
2242 if (empty($arg[0])) {
2243 $listArgs[] = $this->reduce($arg[1]);
2247 return [HTML_Scss_Type::T_FUNCTION, $name, [HTML_Scss_Type::T_LIST, ',', $listArgs]];
2253 * @param string $name
2257 protected function normalizeName($name)
2259 return str_replace('-', '_', $name);
2265 * @param array $value
2269 public function normalizeValue($value)
2271 $value = $this->coerceForExpression($this->reduce($value));
2272 list($type) = $value;
2275 case HTML_Scss_Type::T_LIST:
2276 $value = $this->extractInterpolation($value);
2278 if ($value[0] !== HTML_Scss_Type::T_LIST) {
2279 return [HTML_Scss_Type::T_KEYWORD, $this->compileValue($value)];
2282 foreach ($value[2] as $key => $item) {
2283 $value[2][$key] = $this->normalizeValue($item);
2288 case HTML_Scss_Type::T_STRING:
2289 return [$type, '"', [$this->compileStringContent($value)]];
2291 case HTML_Scss_Type::T_NUMBER:
2292 return $value->normalize();
2294 case HTML_Scss_Type::T_INTERPOLATE:
2295 return [HTML_Scss_Type::T_KEYWORD, $this->compileValue($value)];
2305 * @param array $left
2306 * @param array $right
2308 * @return \Leafo\ScssPhp\Node\Number
2310 protected function opAddNumberNumber($left, $right)
2313 return new HTML_Scss_Node_Number($left[1] + $right[1], $left[2]);
2319 * @param array $left
2320 * @param array $right
2322 * @return \Leafo\ScssPhp\Node\Number
2324 protected function opMulNumberNumber($left, $right)
2326 return new HTML_Scss_Node_Number($left[1] * $right[1], $left[2]);
2332 * @param array $left
2333 * @param array $right
2335 * @return \Leafo\ScssPhp\Node\Number
2337 protected function opSubNumberNumber($left, $right)
2339 return new HTML_Scss_Node_Number($left[1] - $right[1], $left[2]);
2345 * @param array $left
2346 * @param array $right
2348 * @return array|\Leafo\ScssPhp\Node\Number
2350 protected function opDivNumberNumber($left, $right)
2352 if ($right[1] == 0) {
2353 return [HTML_Scss_Type::T_STRING, '', [$left[1] . $left[2] . '/' . $right[1] . $right[2]]];
2356 return new HTML_Scss_Node_Number($left[1] / $right[1], $left[2]);
2362 * @param array $left
2363 * @param array $right
2365 * @return \Leafo\ScssPhp\Node\Number
2367 protected function opModNumberNumber($left, $right)
2369 return new HTML_Scss_Node_Number($left[1] % $right[1], $left[2]);
2375 * @param array $left
2376 * @param array $right
2380 protected function opAdd($left, $right)
2382 if ($strLeft = $this->coerceString($left)) {
2383 if ($right[0] === HTML_Scss_Type::T_STRING) {
2387 $strLeft[2][] = $right;
2392 if ($strRight = $this->coerceString($right)) {
2393 if ($left[0] === HTML_Scss_Type::T_STRING) {
2397 array_unshift($strRight[2], $left);
2406 * @param array $left
2407 * @param array $right
2408 * @param boolean $shouldEval
2412 protected function opAnd($left, $right, $shouldEval)
2414 if (! $shouldEval) {
2418 if ($left !== static::$false and $left !== static::$null) {
2419 return $this->reduce($right, true);
2428 * @param array $left
2429 * @param array $right
2430 * @param boolean $shouldEval
2434 protected function opOr($left, $right, $shouldEval)
2436 if (! $shouldEval) {
2440 if ($left !== static::$false and $left !== static::$null) {
2444 return $this->reduce($right, true);
2451 * @param array $left
2452 * @param array $right
2456 protected function opColorColor($op, $left, $right)
2458 $out = [HTML_Scss_Type::T_COLOR];
2460 foreach ([1, 2, 3] as $i) {
2461 $lval = isset($left[$i]) ? $left[$i] : 0;
2462 $rval = isset($right[$i]) ? $right[$i] : 0;
2466 $out[] = $lval + $rval;
2470 $out[] = $lval - $rval;
2474 $out[] = $lval * $rval;
2478 $out[] = $lval % $rval;
2483 $this->throwError("color: Can't divide by zero");
2487 $out[] = (int) ($lval / $rval);
2491 return $this->opEq($left, $right);
2494 return $this->opNeq($left, $right);
2497 $this->throwError("color: unknown op $op");
2502 if (isset($left[4])) {
2504 } elseif (isset($right[4])) {
2505 $out[4] = $right[4];
2508 return $this->fixColor($out);
2512 * Compare color and number
2515 * @param array $left
2516 * @param array $right
2520 protected function opColorNumber($op, $left, $right)
2524 return $this->opColorColor(
2527 [HTML_Scss_Type::T_COLOR, $value, $value, $value]
2532 * Compare number and color
2535 * @param array $left
2536 * @param array $right
2540 protected function opNumberColor($op, $left, $right)
2544 return $this->opColorColor(
2546 [HTML_Scss_Type::T_COLOR, $value, $value, $value],
2552 * Compare number1 == number2
2554 * @param array $left
2555 * @param array $right
2559 protected function opEq($left, $right)
2561 if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
2565 $left = $this->compileValue($lStr);
2566 $right = $this->compileValue($rStr);
2569 return $this->toBool($left === $right);
2573 * Compare number1 != number2
2575 * @param array $left
2576 * @param array $right
2580 protected function opNeq($left, $right)
2582 if (($lStr = $this->coerceString($left)) && ($rStr = $this->coerceString($right))) {
2586 $left = $this->compileValue($lStr);
2587 $right = $this->compileValue($rStr);
2590 return $this->toBool($left !== $right);
2594 * Compare number1 >= number2
2596 * @param array $left
2597 * @param array $right
2601 protected function opGteNumberNumber($left, $right)
2603 return $this->toBool($left[1] >= $right[1]);
2607 * Compare number1 > number2
2609 * @param array $left
2610 * @param array $right
2614 protected function opGtNumberNumber($left, $right)
2616 return $this->toBool($left[1] > $right[1]);
2620 * Compare number1 <= number2
2622 * @param array $left
2623 * @param array $right
2627 protected function opLteNumberNumber($left, $right)
2629 return $this->toBool($left[1] <= $right[1]);
2633 * Compare number1 < number2
2635 * @param array $left
2636 * @param array $right
2640 protected function opLtNumberNumber($left, $right)
2642 return $this->toBool($left[1] < $right[1]);
2646 * Three-way comparison, aka spaceship operator
2648 * @param array $left
2649 * @param array $right
2651 * @return \Leafo\ScssPhp\Node\Number
2653 protected function opCmpNumberNumber($left, $right)
2655 $n = $left[1] - $right[1];
2657 return new HTML_Scss_Node_Number($n ? $n / abs($n) : 0, '');
2665 * @param mixed $thing
2669 public function toBool($thing)
2671 return $thing ? static::$true : static::$false;
2675 * Compiles a primitive value into a CSS property value.
2677 * Values in scssphp are typed by being wrapped in arrays, their format is
2680 * array(type, contents [, additional_contents]*)
2682 * The input is expected to be reduced. This function will not work on
2683 * things like expressions and variables.
2687 * @param array $value
2691 public function compileValue($value)
2693 //echo "compileValue: "; print_r($value);
2695 $value = $this->reduce($value);
2697 list($type) = $value;
2700 case HTML_Scss_Type::T_KEYWORD:
2703 case HTML_Scss_Type::T_COLOR:
2704 // [1] - red component (either number for a %)
2705 // [2] - green component
2706 // [3] - blue component
2707 // [4] - optional alpha component
2708 list(, $r, $g, $b) = $value;
2714 if (count($value) === 5 && $value[4] !== 1) { // rgba
2715 $a = new HTML_Scss_Node_Number($value[4], '');
2717 return 'rgba(' . $r . ', ' . $g . ', ' . $b . ', ' . $a . ')';
2720 $h = sprintf('#%02x%02x%02x', $r, $g, $b);
2722 // Converting hex color to short notation (e.g. #003399 to #039)
2723 if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
2724 $h = '#' . $h[1] . $h[3] . $h[5];
2729 case HTML_Scss_Type::T_NUMBER:
2730 return $value->output($this);
2732 case HTML_Scss_Type::T_STRING:
2733 return $value[1] . $this->compileStringContent($value) . $value[1];
2735 case HTML_Scss_Type::T_FUNCTION:
2736 $args = ! empty($value[2]) ? $this->compileValue($value[2]) : '';
2738 return "$value[1]($args)";
2740 case HTML_Scss_Type::T_LIST:
2741 $value = $this->extractInterpolation($value);
2743 if ($value[0] !== HTML_Scss_Type::T_LIST) {
2744 return $this->compileValue($value);
2747 list(, $delim, $items) = $value;
2749 if ($delim !== ' ') {
2755 foreach ($items as $item) {
2756 if ($item[0] === HTML_Scss_Type::T_NULL) {
2760 $filtered[] = $this->compileValue($item);
2763 return implode("$delim", $filtered);
2765 case HTML_Scss_Type::T_MAP:
2767 $values = $value[2];
2770 for ($i = 0, $s = count($keys); $i < $s; $i++) {
2771 $filtered[$this->compileValue($keys[$i])] = $this->compileValue($values[$i]);
2774 array_walk($filtered, function (&$value, $key) {
2775 $value = $key . ': ' . $value;
2778 return '(' . implode(', ', $filtered) . ')';
2780 case HTML_Scss_Type::T_INTERPOLATED:
2781 // node created by extractInterpolation
2782 list(, $interpolate, $left, $right) = $value;
2783 list(,, $whiteLeft, $whiteRight) = $interpolate;
2785 $left = count($left[2]) > 0 ?
2786 $this->compileValue($left) . $whiteLeft : '';
2788 $right = count($right[2]) > 0 ?
2789 $whiteRight . $this->compileValue($right) : '';
2791 return $left . $this->compileValue($interpolate) . $right;
2793 case HTML_Scss_Type::T_INTERPOLATE:
2795 list(, $exp) = $value;
2797 // strip quotes if it's a string
2798 $reduced = $this->reduce($exp);
2800 switch ($reduced[0]) {
2801 case HTML_Scss_Type::T_LIST:
2802 $reduced = $this->extractInterpolation($reduced);
2804 if ($reduced[0] !== HTML_Scss_Type::T_LIST) {
2808 list(, $delim, $items) = $reduced;
2810 if ($delim !== ' ') {
2816 foreach ($items as $item) {
2817 if ($item[0] === HTML_Scss_Type::T_NULL) {
2821 $temp = $this->compileValue([HTML_Scss_Type::T_KEYWORD, $item]);
2822 if ($temp[0] === HTML_Scss_Type::T_STRING) {
2823 $filtered[] = $this->compileStringContent($temp);
2824 } elseif ($temp[0] === HTML_Scss_Type::T_KEYWORD) {
2825 $filtered[] = $temp[1];
2827 $filtered[] = $this->compileValue($temp);
2831 $reduced = [HTML_Scss_Type::T_KEYWORD, implode("$delim", $filtered)];
2834 case HTML_Scss_Type::T_STRING:
2835 $reduced = [HTML_Scss_Type::T_KEYWORD, $this->compileStringContent($reduced)];
2838 case HTML_Scss_Type::T_NULL:
2839 $reduced = [HTML_Scss_Type::T_KEYWORD, ''];
2842 return $this->compileValue($reduced);
2844 case HTML_Scss_Type::T_NULL:
2848 $this->throwError("unknown value type: $type");
2855 * @param array $list
2859 protected function flattenList($list)
2861 return $this->compileValue($list);
2865 * Compile string content
2867 * @param array $string
2871 protected function compileStringContent($string)
2874 //echo "compileStringContent: "; print_r($string);
2875 foreach ($string[2] as $part) {
2876 if (is_array($part) || $part instanceof ArrayAccess) {
2877 $parts[] = $this->compileValue($part);
2883 return implode($parts);
2887 * Extract interpolation; it doesn't need to be recursive, compileValue will handle that
2889 * @param array $list
2893 protected function extractInterpolation($list)
2897 foreach ($items as $i => $item) {
2898 if ($item[0] === HTML_Scss_Type::T_INTERPOLATE) {
2899 $before = [HTML_Scss_Type::T_LIST, $list[1], array_slice($items, 0, $i)];
2900 $after = [HTML_Scss_Type::T_LIST, $list[1], array_slice($items, $i + 1)];
2902 return [HTML_Scss_Type::T_INTERPOLATED, $item, $before, $after];
2910 * Find the final set of selectors
2912 * @param \Leafo\ScssPhp\Compiler\Environment $env
2916 protected function multiplySelectors(HTML_Scss_Compiler_Environment $env)
2918 $envs = $this->compactEnv($env);
2920 $parentSelectors = [[]];
2922 while ($env = array_pop($envs)) {
2923 if (empty($env->selectors)) {
2929 foreach ($env->selectors as $selector) {
2930 foreach ($parentSelectors as $parent) {
2931 $selectors[] = $this->joinSelectors($parent, $selector);
2935 $parentSelectors = $selectors;
2942 * Join selectors; looks for & to replace, or append parent before child
2944 * @param array $parent
2945 * @param array $child
2949 protected function joinSelectors($parent, $child)
2954 foreach ($child as $part) {
2957 foreach ($part as $p) {
2958 if ($p === static::$selfSelector) {
2961 foreach ($parent as $i => $parentPart) {
2967 foreach ($parentPart as $pp) {
2979 return $setSelf ? $out : array_merge($parent, $child);
2985 * @param \Leafo\ScssPhp\Compiler\Environment $env
2986 * @param array $childQueries
2990 protected function multiplyMedia(HTML_Scss_Compiler_Environment $env = null, $childQueries = null)
2992 if (! isset($env) ||
2993 ! empty($env->block->type) && $env->block->type !== HTML_Scss_Type::T_MEDIA
2995 return $childQueries;
2998 // plain old block, skip
2999 if (empty($env->block->type)) {
3000 return $this->multiplyMedia($env->parent, $childQueries);
3003 $parentQueries = isset($env->block->queryList)
3004 ? $env->block->queryList
3005 : [[[HTML_Scss_Type::T_MEDIA_VALUE, $env->block->value]]];
3007 if ($childQueries === null) {
3008 $childQueries = $parentQueries;
3010 $originalQueries = $childQueries;
3013 foreach ($parentQueries as $parentQuery) {
3014 foreach ($originalQueries as $childQuery) {
3015 $childQueries []= array_merge($parentQuery, $childQuery);
3020 return $this->multiplyMedia($env->parent, $childQueries);
3024 * Convert env linked list to stack
3026 * @param \Leafo\ScssPhp\Compiler\Environment $env
3030 private function compactEnv(HTML_Scss_Compiler_Environment $env)
3032 for ($envs = []; $env; $env = $env->parent) {
3040 * Convert env stack to singly linked list
3042 * @param array $envs
3044 * @return \Leafo\ScssPhp\Compiler\Environment
3046 private function extractEnv($envs)
3048 for ($env = null; $e = array_pop($envs);) {
3059 * @param \Leafo\ScssPhp\Block $block
3061 * @return \Leafo\ScssPhp\Compiler\Environment
3063 protected function pushEnv(HTML_Scss_Block $block = null)
3065 $env = new HTML_Scss_Compiler_Environment;
3066 $env->parent = $this->env;
3068 $env->block = $block;
3069 $env->depth = isset($this->env->depth) ? $this->env->depth + 1 : 0;
3079 protected function popEnv()
3081 $this->env = $this->env->parent;
3085 * Get store environment
3087 * @return \Leafo\ScssPhp\Compiler\Environment
3089 protected function getStoreEnv()
3091 return isset($this->storeEnv) ? $this->storeEnv : $this->env;
3097 * @param string $name
3098 * @param mixed $value
3099 * @param boolean $shadow
3100 * @param \Leafo\ScssPhp\Compiler\Environment $env
3102 protected function set($name, $value, $shadow = false, HTML_Scss_Compiler_Environment $env = null)
3104 $name = $this->normalizeName($name);
3106 if (! isset($env)) {
3107 $env = $this->getStoreEnv();
3111 $this->setRaw($name, $value, $env);
3113 $this->setExisting($name, $value, $env);
3118 * Set existing variable
3120 * @param string $name
3121 * @param mixed $value
3122 * @param \Leafo\ScssPhp\Compiler\Environment $env
3124 protected function setExisting($name, $value, HTML_Scss_Compiler_Environment $env)
3128 $hasNamespace = $name[0] === '^' || $name[0] === '@' || $name[0] === '%';
3131 if (array_key_exists($name, $env->store)) {
3135 if (! $hasNamespace && isset($env->marker)) {
3140 if (! isset($env->parent)) {
3145 $env = $env->parent;
3148 $env->store[$name] = $value;
3154 * @param string $name
3155 * @param mixed $value
3156 * @param \Leafo\ScssPhp\Compiler\Environment $env
3158 protected function setRaw($name, $value, HTML_Scss_Compiler_Environment $env)
3160 $env->store[$name] = $value;
3168 * @param string $name
3169 * @param boolean $shouldThrow
3170 * @param \Leafo\ScssPhp\Compiler\Environment $env
3174 public function get($name, $shouldThrow = true, HTML_Scss_Compiler_Environment $env = null)
3176 $normalizedName = $this->normalizeName($name);
3177 $specialContentKey = static::$namespaces['special'] . 'content';
3179 if (! isset($env)) {
3180 $env = $this->getStoreEnv();
3183 $nextIsRoot = false;
3184 $hasNamespace = $normalizedName[0] === '^' || $normalizedName[0] === '@' || $normalizedName[0] === '%';
3187 if (array_key_exists($normalizedName, $env->store)) {
3188 return $env->store[$normalizedName];
3191 if (! $hasNamespace && isset($env->marker)) {
3192 if (! $nextIsRoot && ! empty($env->store[$specialContentKey])) {
3193 $env = $env->store[$specialContentKey]->scope;
3198 $env = $this->rootEnv;
3202 if (! isset($env->parent)) {
3206 $env = $env->parent;
3210 $this->throwError("Undefined variable \$$name");
3219 * @param string $name
3220 * @param \Leafo\ScssPhp\Compiler\Environment $env
3224 protected function has($name, HTML_Scss_Compiler_Environment $env = null)
3226 return $this->get($name, false, $env) !== null;
3232 * @param array $args
3234 protected function injectVariables(array $args)
3240 $parser = $this->parserFactory(__METHOD__);
3242 foreach ($args as $name => $strValue) {
3243 if ($name[0] === '$') {
3244 $name = substr($name, 1);
3247 if (! $parser->parseValue($strValue, $value)) {
3248 $value = $this->coerceValue($strValue);
3251 $this->set($name, $value);
3260 * @param array $variables
3262 public function setVariables(array $variables)
3264 $this->registeredVars = array_merge($this->registeredVars, $variables);
3272 * @param string $name
3274 public function unsetVariable($name)
3276 unset($this->registeredVars[$name]);
3280 * Returns list of variables
3286 public function getVariables()
3288 return $this->registeredVars;
3292 * Adds to list of parsed files
3296 * @param string $path
3298 public function addParsedFile($path)
3300 if (isset($path) && file_exists($path)) {
3301 $this->parsedFiles[realpath($path)] = filemtime($path);
3306 * Returns list of parsed files
3312 public function getParsedFiles()
3314 return $this->parsedFiles;
3322 * @param string|callable $path
3324 public function addImportPath($path)
3326 if (! in_array($path, $this->importPaths)) {
3327 $this->importPaths[] = $path;
3336 * @param string|array $path
3338 public function setImportPaths($path)
3340 $this->importPaths = (array) $path;
3344 * Set number precision
3348 * @param integer $numberPrecision
3350 public function setNumberPrecision($numberPrecision)
3352 HTML_Scss_Node_Number::$precision = $numberPrecision;
3360 * @param string $formatterName
3362 public function setFormatter($formatterName)
3364 $this->formatter = $formatterName;
3368 * Set line number style
3372 * @param string $lineNumberStyle
3374 public function setLineNumberStyle($lineNumberStyle)
3376 $this->lineNumberStyle = $lineNumberStyle;
3380 * Enable/disable source maps
3384 * @param integer $sourceMap
3386 public function setSourceMap($sourceMap)
3388 $this->sourceMap = $sourceMap;
3392 * Set source map options
3396 * @param array $sourceMapOptions
3398 public function setSourceMapOptions($sourceMapOptions)
3400 $this->sourceMapOptions = $sourceMapOptions;
3408 * @param string $name
3409 * @param callable $func
3410 * @param array $prototype
3412 public function registerFunction($name, $func, $prototype = null)
3414 $this->userFunctions[$this->normalizeName($name)] = [$func, $prototype];
3418 * Unregister function
3422 * @param string $name
3424 public function unregisterFunction($name)
3426 unset($this->userFunctions[$this->normalizeName($name)]);
3434 * @param string $name
3436 public function addFeature($name)
3438 $this->registeredFeatures[$name] = true;
3444 * @param string $path
3447 protected function importFile($path, $out)
3449 // see if tree is cached
3450 $realPath = realpath($path);
3452 if (isset($this->importCache[$realPath])) {
3453 $this->handleImportLoop($realPath);
3455 $tree = $this->importCache[$realPath];
3457 $code = file_get_contents($path);
3458 $parser = $this->parserFactory($path);
3459 $tree = $parser->parse($code);
3461 $this->importCache[$realPath] = $tree;
3464 $pi = pathinfo($path);
3465 array_unshift($this->importPaths, $pi['dirname']);
3466 $this->compileChildrenNoReturn($tree->children, $out);
3467 array_shift($this->importPaths);
3471 * Return the file path for an import url if it exists
3475 * @param string $url
3477 * @return string|null
3479 public function findImport($url)
3483 // for "normal" scss imports (ignore vanilla css and external requests)
3484 if (! preg_match('/\.css$|^https?:\/\//', $url)) {
3485 // try both normal and the _partial filename
3486 $urls = [$url, preg_replace('/[^\/]+$/', '_\0', $url)];
3489 $hasExtension = preg_match('/[.]s?css$/', $url);
3491 foreach ($this->importPaths as $dir) {
3492 if (is_string($dir)) {
3493 // check urls for normal import paths
3494 foreach ($urls as $full) {
3496 . (! empty($dir) && substr($dir, -1) !== '/' ? '/' : '')
3499 if ($this->fileExists($file = $full . '.scss') ||
3500 ($hasExtension && $this->fileExists($file = $full))
3505 } elseif (is_callable($dir)) {
3506 // check custom callback for import path
3507 $file = call_user_func($dir, $url);
3509 if ($file !== null) {
3523 * @param string $encoding
3525 public function setEncoding($encoding)
3527 $this->encoding = $encoding;
3535 * @param boolean $ignoreErrors
3537 * @return \Leafo\ScssPhp\Compiler
3539 public function setIgnoreErrors($ignoreErrors)
3541 $this->ignoreErrors = $ignoreErrors;
3545 * Throw error (exception)
3549 * @param string $msg Message with optional sprintf()-style vararg parameters
3551 * @throws \Leafo\ScssPhp\Exception\CompilerException
3553 public function throwError($msg)
3555 if ($this->ignoreErrors) {
3559 if (func_num_args() > 1) {
3560 $msg = call_user_func_array('sprintf', func_get_args());
3563 $line = $this->sourceLine;
3564 $msg = "$msg: line: $line";
3565 require_once 'Scss/Exception/CompilerException.php';
3566 throw new HTML_Scss_Exception_CompilerException($msg);
3570 * Handle import loop
3572 * @param string $name
3574 * @throws \Exception
3576 protected function handleImportLoop($name)
3578 for ($env = $this->env; $env; $env = $env->parent) {
3579 $file = $this->sourceNames[$env->block->sourceIndex];
3581 if (realpath($file) === $name) {
3582 $this->throwError('An @import loop has been found: %s imports %s', $file, basename($file));
3591 * @param string $name
3595 protected function fileExists($name)
3597 return file_exists($name) && is_file($name);
3601 * Call SCSS @function
3603 * @param string $name
3604 * @param array $argValues
3605 * @param array $returnValue
3607 * @return boolean Returns true if returnValue is set; otherwise, false
3609 protected function callScssFunction($name, $argValues, &$returnValue)
3611 $func = $this->get(static::$namespaces['function'] . $name, false);
3619 $storeEnv = $this->storeEnv;
3620 $this->storeEnv = $this->env;
3623 if (isset($func->args)) {
3624 $this->applyArguments($func->args, $argValues);
3627 // throw away lines and children
3628 $tmp = new HTML_Scss_Formatter_OutputBlock;
3630 $tmp->children = [];
3632 $this->env->marker = 'function';
3634 $ret = $this->compileChildren($func->children, $tmp);
3636 $this->storeEnv = $storeEnv;
3640 $returnValue = ! isset($ret) ? static::$defaultValue : $ret;
3646 * Call built-in and registered (PHP) functions
3648 * @param string $name
3649 * @param array $args
3650 * @param array $returnValue
3652 * @return boolean Returns true if returnValue is set; otherwise, false
3654 protected function callNativeFunction($name, $args, &$returnValue)
3656 // try a lib function
3657 $name = $this->normalizeName($name);
3659 if (isset($this->userFunctions[$name])) {
3660 // see if we can find a user function
3661 list($f, $prototype) = $this->userFunctions[$name];
3662 } elseif (($f = $this->getBuiltinFunction($name)) && is_callable($f)) {
3664 $prototype = isset(static::$$libName) ? static::$$libName : null;
3669 @list($sorted, $kwargs) = $this->sortArgs($prototype, $args);
3671 if ($name !== 'if' && $name !== 'call') {
3672 foreach ($sorted as &$val) {
3673 $val = $this->reduce($val, true);
3677 $returnValue = call_user_func($f, $sorted, $kwargs);
3679 if (! isset($returnValue)) {
3683 $returnValue = $this->coerceValue($returnValue);
3689 * Get built-in function
3691 * @param string $name Normalized name
3695 protected function getBuiltinFunction($name)
3697 $libName = 'lib' . preg_replace_callback(
3700 return ucfirst($m[1]);
3705 return [$this, $libName];
3709 * Sorts keyword arguments
3711 * @param array $prototype
3712 * @param array $args
3716 protected function sortArgs($prototype, $args)
3721 // separate positional and keyword arguments
3722 foreach ($args as $arg) {
3723 list($key, $value) = $arg;
3728 $posArgs[] = empty($arg[2]) ? $value : $arg;
3730 $keyArgs[$key] = $value;
3734 if (! isset($prototype)) {
3735 return [$posArgs, $keyArgs];
3738 // copy positional args
3739 $finalArgs = array_pad($posArgs, count($prototype), null);
3741 // overwrite positional args with keyword args
3742 foreach ($prototype as $i => $names) {
3743 foreach ((array) $names as $name) {
3744 if (isset($keyArgs[$name])) {
3745 $finalArgs[$i] = $keyArgs[$name];
3750 return [$finalArgs, $keyArgs];
3754 * Apply argument values per definition
3756 * @param array $argDef
3757 * @param array $argValues
3759 * @throws \Exception
3761 protected function applyArguments($argDef, $argValues)
3763 $storeEnv = $this->getStoreEnv();
3765 $env = new HTML_Scss_Compiler_Environment;
3766 $env->store = $storeEnv->store;
3768 $hasVariable = false;
3771 foreach ($argDef as $i => $arg) {
3772 list($name, $default, $isVariable) = $argDef[$i];
3774 $args[$name] = [$i, $name, $default, $isVariable];
3775 $hasVariable |= $isVariable;
3779 $deferredKeywordArgs = [];
3782 // assign the keyword args
3783 foreach ((array) $argValues as $arg) {
3784 if (! empty($arg[0])) {
3785 if (! isset($args[$arg[0][1]])) {
3787 $deferredKeywordArgs[$arg[0][1]] = $arg[1];
3789 $this->throwError("Mixin or function doesn't have an argument named $%s.", $arg[0][1]);
3792 } elseif ($args[$arg[0][1]][0] < count($remaining)) {
3793 $this->throwError("The argument $%s was passed both by position and by name.", $arg[0][1]);
3796 $keywordArgs[$arg[0][1]] = $arg[1];
3798 } elseif (count($keywordArgs)) {
3799 $this->throwError('Positional arguments must come before keyword arguments.');
3801 } elseif ($arg[2] === true) {
3802 $val = $this->reduce($arg[1], true);
3804 if ($val[0] === HTML_Scss_Type::T_LIST) {
3805 foreach ($val[2] as $name => $item) {
3806 if (! is_numeric($name)) {
3807 $keywordArgs[$name] = $item;
3809 $remaining[] = $item;
3812 } elseif ($val[0] === HTML_Scss_Type::T_MAP) {
3813 foreach ($val[1] as $i => $name) {
3814 $name = $this->compileStringContent($this->coerceString($name));
3815 $item = $val[2][$i];
3817 if (! is_numeric($name)) {
3818 $keywordArgs[$name] = $item;
3820 $remaining[] = $item;
3824 $remaining[] = $val;
3827 $remaining[] = $arg[1];
3831 foreach ($args as $arg) {
3832 list($i, $name, $default, $isVariable) = $arg;
3835 $val = [HTML_Scss_Type::T_LIST, ',', [], $isVariable];
3837 for ($count = count($remaining); $i < $count; $i++) {
3838 $val[2][] = $remaining[$i];
3841 foreach ($deferredKeywordArgs as $itemName => $item) {
3842 $val[2][$itemName] = $item;
3844 } elseif (isset($remaining[$i])) {
3845 $val = $remaining[$i];
3846 } elseif (isset($keywordArgs[$name])) {
3847 $val = $keywordArgs[$name];
3848 } elseif (! empty($default)) {
3851 $this->throwError("Missing argument $name");
3855 $this->set($name, $this->reduce($val, true), true, $env);
3858 $storeEnv->store = $env->store;
3860 foreach ($args as $arg) {
3861 list($i, $name, $default, $isVariable) = $arg;
3863 if ($isVariable || isset($remaining[$i]) || isset($keywordArgs[$name]) || empty($default)) {
3867 $this->set($name, $this->reduce($default, true), true);
3872 * Coerce a php value into a scss one
3874 * @param mixed $value
3876 * @return array|\Leafo\ScssPhp\Node\Number
3878 private function coerceValue($value)
3880 if (is_array($value) || $value instanceof ArrayAccess) {
3884 if (is_bool($value)) {
3885 return $this->toBool($value);
3888 if ($value === null) {
3889 return static::$null;
3892 if (is_numeric($value)) {
3893 return new HTML_Scss_Node_Number($value, '');
3896 if ($value === '') {
3897 return static::$emptyString;
3900 if (preg_match('/^(#([0-9a-f]{6})|#([0-9a-f]{3}))$/i', $value, $m)) {
3901 $color = [HTML_Scss_Type::T_COLOR];
3904 $num = hexdec($m[3]);
3906 foreach ([3, 2, 1] as $i) {
3908 $color[$i] = $t << 4 | $t;
3912 $num = hexdec($m[2]);
3914 foreach ([3, 2, 1] as $i) {
3915 $color[$i] = $num & 0xff;
3923 return [HTML_Scss_Type::T_KEYWORD, $value];
3927 * Coerce something to map
3929 * @param array $item
3933 protected function coerceMap($item)
3935 if ($item[0] === HTML_Scss_Type::T_MAP) {
3939 if ($item === static::$emptyList) {
3940 return static::$emptyMap;
3943 return [HTML_Scss_Type::T_MAP, [$item], [static::$null]];
3947 * Coerce something to list
3949 * @param array $item
3950 * @param string $delim
3954 protected function coerceList($item, $delim = ',')
3956 if (isset($item) && $item[0] === HTML_Scss_Type::T_LIST) {
3960 if (isset($item) && $item[0] === HTML_Scss_Type::T_MAP) {
3965 for ($i = 0, $s = count($keys); $i < $s; $i++) {
3967 $value = $values[$i];
3970 HTML_Scss_Type::T_LIST,
3972 [[HTML_Scss_Type::T_KEYWORD, $this->compileStringContent($this->coerceString($key))], $value]
3976 return [HTML_Scss_Type::T_LIST, ',', $list];
3979 return [HTML_Scss_Type::T_LIST, $delim, ! isset($item) ? []: [$item]];
3983 * Coerce color for expression
3985 * @param array $value
3987 * @return array|null
3989 protected function coerceForExpression($value)
3991 if ($color = $this->coerceColor($value)) {
3999 * Coerce value to color
4001 * @param array $value
4003 * @return array|null
4005 protected function coerceColor($value)
4007 switch ($value[0]) {
4008 case HTML_Scss_Type::T_COLOR:
4011 case HTML_Scss_Type::T_KEYWORD:
4012 $name = strtolower($value[1]);
4014 if (isset(HTML_Scss_Colors::$cssColors[$name])) {
4015 $rgba = explode(',', HTML_Scss_Colors::$cssColors[$name]);
4017 return isset($rgba[3])
4018 ? [HTML_Scss_Type::T_COLOR, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2], (int) $rgba[3]]
4019 : [HTML_Scss_Type::T_COLOR, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2]];
4029 * Coerce value to string
4031 * @param array $value
4033 * @return array|null
4035 protected function coerceString($value)
4037 if ($value[0] === HTML_Scss_Type::T_STRING) {
4041 return [HTML_Scss_Type::T_STRING, '', [$this->compileValue($value)]];
4045 * Coerce value to a percentage
4047 * @param array $value
4049 * @return integer|float
4051 protected function coercePercent($value)
4053 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4054 if (! empty($value[2]['%'])) {
4055 return $value[1] / 100;
4065 * Assert value is a map
4069 * @param array $value
4073 * @throws \Exception
4075 public function assertMap($value)
4077 $value = $this->coerceMap($value);
4079 if ($value[0] !== HTML_Scss_Type::T_MAP) {
4080 $this->throwError('expecting map');
4087 * Assert value is a list
4091 * @param array $value
4095 * @throws \Exception
4097 public function assertList($value)
4099 if ($value[0] !== HTML_Scss_Type::T_LIST) {
4100 $this->throwError('expecting list');
4107 * Assert value is a color
4111 * @param array $value
4115 * @throws \Exception
4117 public function assertColor($value)
4119 if ($color = $this->coerceColor($value)) {
4123 $this->throwError('expecting color');
4127 * Assert value is a number
4131 * @param array $value
4133 * @return integer|float
4135 * @throws \Exception
4137 public function assertNumber($value)
4139 if ($value[0] !== HTML_Scss_Type::T_NUMBER) {
4140 $this->throwError('expecting number');
4147 * Make sure a color's components don't go out of bounds
4153 protected function fixColor($c)
4155 foreach ([1, 2, 3] as $i) {
4169 * Convert RGB to HSL
4173 * @param integer $red
4174 * @param integer $green
4175 * @param integer $blue
4179 public function toHSL($red, $green, $blue)
4181 $min = min($red, $green, $blue);
4182 $max = max($red, $green, $blue);
4187 if ((int) $d === 0) {
4193 $s = $d / (510 - $l);
4197 $h = 60 * ($green - $blue) / $d;
4198 } elseif ($green == $max) {
4199 $h = 60 * ($blue - $red) / $d + 120;
4200 } elseif ($blue == $max) {
4201 $h = 60 * ($red - $green) / $d + 240;
4205 return [HTML_Scss_Type::T_HSL, fmod($h, 360), $s * 100, $l / 5.1];
4217 private function hueToRGB($m1, $m2, $h)
4226 return $m1 + ($m2 - $m1) * $h * 6;
4234 return $m1 + ($m2 - $m1) * (2/3 - $h) * 6;
4241 * Convert HSL to RGB
4245 * @param integer $hue H from 0 to 360
4246 * @param integer $saturation S from 0 to 100
4247 * @param integer $lightness L from 0 to 100
4251 public function toRGB($hue, $saturation, $lightness)
4258 $s = min(100, max(0, $saturation)) / 100;
4259 $l = min(100, max(0, $lightness)) / 100;
4261 $m2 = $l <= 0.5 ? $l * ($s + 1) : $l + $s - $l * $s;
4264 $r = $this->hueToRGB($m1, $m2, $h + 1/3) * 255;
4265 $g = $this->hueToRGB($m1, $m2, $h) * 255;
4266 $b = $this->hueToRGB($m1, $m2, $h - 1/3) * 255;
4268 $out = [HTML_Scss_Type::T_COLOR, $r, $g, $b];
4273 // Built in functions
4275 //protected static $libCall = ['name', 'args...'];
4276 protected function libCall($args, $kwargs)
4278 $name = $this->compileStringContent($this->coerceString($this->reduce(array_shift($args), true)));
4282 foreach ($args as $arg) {
4283 if (empty($arg[0])) {
4284 if ($arg[2] === true) {
4285 $tmp = $this->reduce($arg[1]);
4287 if ($tmp[0] === HTML_Scss_Type::T_LIST) {
4288 foreach ($tmp[2] as $item) {
4289 $posArgs[] = [null, $item, false];
4292 $posArgs[] = [null, $tmp, true];
4298 $posArgs[] = [null, $this->reduce($arg), false];
4302 $posArgs[] = [null, $arg, false];
4305 if (count($kwargs)) {
4306 foreach ($kwargs as $key => $value) {
4307 $posArgs[] = [[HTML_Scss_Type::T_VARIABLE, $key], $value, false];
4311 return $this->reduce([HTML_Scss_Type::T_FUNCTION_CALL, $name, $posArgs]);
4314 protected static $libIf = ['condition', 'if-true', 'if-false'];
4315 protected function libIf($args)
4317 list($cond, $t, $f) = $args;
4319 if (! $this->isTruthy($this->reduce($cond, true))) {
4320 return $this->reduce($f, true);
4323 return $this->reduce($t, true);
4326 protected static $libIndex = ['list', 'value'];
4327 protected function libIndex($args)
4329 list($list, $value) = $args;
4331 if ($value[0] === HTML_Scss_Type::T_MAP) {
4332 return static::$null;
4335 if ($list[0] === HTML_Scss_Type::T_MAP ||
4336 $list[0] === HTML_Scss_Type::T_STRING ||
4337 $list[0] === HTML_Scss_Type::T_KEYWORD ||
4338 $list[0] === HTML_Scss_Type::T_INTERPOLATE
4340 $list = $this->coerceList($list, ' ');
4343 if ($list[0] !== HTML_Scss_Type::T_LIST) {
4344 return static::$null;
4349 foreach ($list[2] as $item) {
4350 $values[] = $this->normalizeValue($item);
4353 $key = array_search($this->normalizeValue($value), $values);
4355 return false === $key ? static::$null : $key + 1;
4358 protected static $libRgb = ['red', 'green', 'blue'];
4359 protected function libRgb($args)
4361 list($r, $g, $b) = $args;
4363 return [HTML_Scss_Type::T_COLOR, $r[1], $g[1], $b[1]];
4366 protected static $libRgba = [
4368 'green', 'blue', 'alpha'];
4369 protected function libRgba($args)
4371 if ($color = $this->coerceColor($args[0])) {
4372 $num = isset($args[3]) ? $args[3] : $args[1];
4373 $alpha = $this->assertNumber($num);
4379 list($r, $g, $b, $a) = $args;
4381 return [HTML_Scss_Type::T_COLOR, $r[1], $g[1], $b[1], $a[1]];
4384 // helper function for adjust_color, change_color, and scale_color
4385 protected function alterColor($args, $fn)
4387 $color = $this->assertColor($args[0]);
4389 foreach ([1, 2, 3, 7] as $i) {
4390 if (isset($args[$i])) {
4391 $val = $this->assertNumber($args[$i]);
4392 $ii = $i === 7 ? 4 : $i; // alpha
4393 $color[$ii] = call_user_func($fn, isset($color[$ii]) ? $color[$ii] : 0, $val, $i);
4397 if (isset($args[4]) || isset($args[5]) || isset($args[6])) {
4398 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4400 foreach ([4, 5, 6] as $i) {
4401 if (isset($args[$i])) {
4402 $val = $this->assertNumber($args[$i]);
4403 $hsl[$i - 3] = call_user_func($fn, $hsl[$i - 3], $val, $i);
4407 $rgb = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
4409 if (isset($color[4])) {
4410 $rgb[4] = $color[4];
4419 protected static $libAdjustColor = [
4420 'color', 'red', 'green', 'blue',
4421 'hue', 'saturation', 'lightness', 'alpha'
4423 protected function libAdjustColor($args)
4425 return $this->alterColor($args, function ($base, $alter, $i) {
4426 return $base + $alter;
4430 protected static $libChangeColor = [
4431 'color', 'red', 'green', 'blue',
4432 'hue', 'saturation', 'lightness', 'alpha'
4434 protected function libChangeColor($args)
4436 return $this->alterColor($args, function ($base, $alter, $i) {
4441 protected static $libScaleColor = [
4442 'color', 'red', 'green', 'blue',
4443 'hue', 'saturation', 'lightness', 'alpha'
4445 protected function libScaleColor($args)
4447 return $this->alterColor($args, function ($base, $scale, $i) {
4470 $scale = $scale / 100;
4473 return $base * $scale + $base;
4476 return ($max - $base) * $scale + $base;
4480 protected static $libIeHexStr = ['color'];
4481 protected function libIeHexStr($args)
4483 $color = $this->coerceColor($args[0]);
4484 $color[4] = isset($color[4]) ? round(255 * $color[4]) : 255;
4486 return sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3]);
4489 protected static $libRed = ['color'];
4490 protected function libRed($args)
4492 $color = $this->coerceColor($args[0]);
4497 protected static $libGreen = ['color'];
4498 protected function libGreen($args)
4500 $color = $this->coerceColor($args[0]);
4505 protected static $libBlue = ['color'];
4506 protected function libBlue($args)
4508 $color = $this->coerceColor($args[0]);
4513 protected static $libAlpha = ['color'];
4514 protected function libAlpha($args)
4516 if ($color = $this->coerceColor($args[0])) {
4517 return isset($color[4]) ? $color[4] : 1;
4520 // this might be the IE function, so return value unchanged
4524 protected static $libOpacity = ['color'];
4525 protected function libOpacity($args)
4529 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4533 return $this->libAlpha($args);
4537 protected static $libMix = ['color-1', 'color-2', 'weight'];
4538 protected function libMix($args)
4540 list($first, $second, $weight) = $args;
4542 $first = $this->assertColor($first);
4543 $second = $this->assertColor($second);
4545 if (! isset($weight)) {
4548 $weight = $this->coercePercent($weight);
4551 $firstAlpha = isset($first[4]) ? $first[4] : 1;
4552 $secondAlpha = isset($second[4]) ? $second[4] : 1;
4554 $w = $weight * 2 - 1;
4555 $a = $firstAlpha - $secondAlpha;
4557 $w1 = (($w * $a === -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
4560 $new = [HTML_Scss_Type::T_COLOR,
4561 $w1 * $first[1] + $w2 * $second[1],
4562 $w1 * $first[2] + $w2 * $second[2],
4563 $w1 * $first[3] + $w2 * $second[3],
4566 if ($firstAlpha != 1.0 || $secondAlpha != 1.0) {
4567 $new[] = $firstAlpha * $weight + $secondAlpha * (1 - $weight);
4570 return $this->fixColor($new);
4573 protected static $libHsl = ['hue', 'saturation', 'lightness'];
4574 protected function libHsl($args)
4576 list($h, $s, $l) = $args;
4578 return $this->toRGB($h[1], $s[1], $l[1]);
4581 protected static $libHsla = ['hue', 'saturation', 'lightness', 'alpha'];
4582 protected function libHsla($args)
4584 list($h, $s, $l, $a) = $args;
4586 $color = $this->toRGB($h[1], $s[1], $l[1]);
4592 protected static $libHue = ['color'];
4593 protected function libHue($args)
4595 $color = $this->assertColor($args[0]);
4596 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4598 return new HTML_Scss_Node_Number($hsl[1], 'deg');
4601 protected static $libSaturation = ['color'];
4602 protected function libSaturation($args)
4604 $color = $this->assertColor($args[0]);
4605 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4607 return new HTML_Scss_Node_Number($hsl[2], '%');
4610 protected static $libLightness = ['color'];
4611 protected function libLightness($args)
4613 $color = $this->assertColor($args[0]);
4614 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4616 return new HTML_Scss_Node_Number($hsl[3], '%');
4619 protected function adjustHsl($color, $idx, $amount)
4621 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4622 $hsl[$idx] += $amount;
4623 $out = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
4625 if (isset($color[4])) {
4626 $out[4] = $color[4];
4632 protected static $libAdjustHue = ['color', 'degrees'];
4633 protected function libAdjustHue($args)
4635 $color = $this->assertColor($args[0]);
4636 $degrees = $this->assertNumber($args[1]);
4638 return $this->adjustHsl($color, 1, $degrees);
4641 protected static $libLighten = ['color', 'amount'];
4642 protected function libLighten($args)
4644 $color = $this->assertColor($args[0]);
4645 require_once 'Scss/Base/Range.php';
4646 $amount = HTML_Scss_Util::checkRange('amount', new HTML_Scss_Base_Range(0, 100), $args[1], '%');
4648 return $this->adjustHsl($color, 3, $amount);
4651 protected static $libDarken = ['color', 'amount'];
4652 protected function libDarken($args)
4654 $color = $this->assertColor($args[0]);
4655 require_once 'Scss/Base/Range.php';
4656 $amount = HTML_Scss_Util::checkRange('amount', new HTML_Scss_Base_Range(0, 100), $args[1], '%');
4658 return $this->adjustHsl($color, 3, -$amount);
4661 protected static $libSaturate = ['color', 'amount'];
4662 protected function libSaturate($args)
4666 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4670 $color = $this->assertColor($value);
4671 $amount = 100 * $this->coercePercent($args[1]);
4673 return $this->adjustHsl($color, 2, $amount);
4676 protected static $libDesaturate = ['color', 'amount'];
4677 protected function libDesaturate($args)
4679 $color = $this->assertColor($args[0]);
4680 $amount = 100 * $this->coercePercent($args[1]);
4682 return $this->adjustHsl($color, 2, -$amount);
4685 protected static $libGrayscale = ['color'];
4686 protected function libGrayscale($args)
4690 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4694 return $this->adjustHsl($this->assertColor($value), 2, -100);
4697 protected static $libComplement = ['color'];
4698 protected function libComplement($args)
4700 return $this->adjustHsl($this->assertColor($args[0]), 1, 180);
4703 protected static $libInvert = ['color'];
4704 protected function libInvert($args)
4708 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4712 $color = $this->assertColor($value);
4713 $color[1] = 255 - $color[1];
4714 $color[2] = 255 - $color[2];
4715 $color[3] = 255 - $color[3];
4720 // increases opacity by amount
4721 protected static $libOpacify = ['color', 'amount'];
4722 protected function libOpacify($args)
4724 $color = $this->assertColor($args[0]);
4725 $amount = $this->coercePercent($args[1]);
4727 $color[4] = (isset($color[4]) ? $color[4] : 1) + $amount;
4728 $color[4] = min(1, max(0, $color[4]));
4733 protected static $libFadeIn = ['color', 'amount'];
4734 protected function libFadeIn($args)
4736 return $this->libOpacify($args);
4739 // decreases opacity by amount
4740 protected static $libTransparentize = ['color', 'amount'];
4741 protected function libTransparentize($args)
4743 $color = $this->assertColor($args[0]);
4744 $amount = $this->coercePercent($args[1]);
4746 $color[4] = (isset($color[4]) ? $color[4] : 1) - $amount;
4747 $color[4] = min(1, max(0, $color[4]));
4752 protected static $libFadeOut = ['color', 'amount'];
4753 protected function libFadeOut($args)
4755 return $this->libTransparentize($args);
4758 protected static $libUnquote = ['string'];
4759 protected function libUnquote($args)
4763 if ($str[0] === HTML_Scss_Type::T_STRING) {
4770 protected static $libQuote = ['string'];
4771 protected function libQuote($args)
4775 if ($value[0] === HTML_Scss_Type::T_STRING && ! empty($value[1])) {
4779 return [HTML_Scss_Type::T_STRING, '"', [$value]];
4782 protected static $libPercentage = ['value'];
4783 protected function libPercentage($args)
4785 return new HTML_Scss_Node_Number($this->coercePercent($args[0]) * 100, '%');
4788 protected static $libRound = ['value'];
4789 protected function libRound($args)
4793 return new HTML_Scss_Node_Number(round($num[1]), $num[2]);
4796 protected static $libFloor = ['value'];
4797 protected function libFloor($args)
4801 return new HTML_Scss_Node_Number(floor($num[1]), $num[2]);
4804 protected static $libCeil = ['value'];
4805 protected function libCeil($args)
4809 return new HTML_Scss_Node_Number(ceil($num[1]), $num[2]);
4812 protected static $libAbs = ['value'];
4813 protected function libAbs($args)
4817 return new HTML_Scss_Node_Number(abs($num[1]), $num[2]);
4820 protected function libMin($args)
4822 $numbers = $this->getNormalizedNumbers($args);
4825 foreach ($numbers as $key => $number) {
4826 if (null === $min || $number[1] <= $min[1]) {
4827 $min = [$key, $number[1]];
4831 return $args[$min[0]];
4834 protected function libMax($args)
4836 $numbers = $this->getNormalizedNumbers($args);
4839 foreach ($numbers as $key => $number) {
4840 if (null === $max || $number[1] >= $max[1]) {
4841 $max = [$key, $number[1]];
4845 return $args[$max[0]];
4849 * Helper to normalize args containing numbers
4851 * @param array $args
4855 protected function getNormalizedNumbers($args)
4858 $originalUnit = null;
4861 foreach ($args as $key => $item) {
4862 if ($item[0] !== HTML_Scss_Type::T_NUMBER) {
4863 $this->throwError('%s is not a number', $item[0]);
4867 $number = $item->normalize();
4869 if (null === $unit) {
4871 $originalUnit = $item->unitStr();
4872 } elseif ($number[1] && $unit !== $number[2]) {
4873 $this->throwError('Incompatible units: "%s" and "%s".', $originalUnit, $item->unitStr());
4877 $numbers[$key] = $number;
4883 protected static $libLength = ['list'];
4884 protected function libLength($args)
4886 $list = $this->coerceList($args[0]);
4888 return count($list[2]);
4891 //protected static $libListSeparator = ['list...'];
4892 protected function libListSeparator($args)
4894 if (count($args) > 1) {
4898 $list = $this->coerceList($args[0]);
4900 if (count($list[2]) <= 1) {
4904 if ($list[1] === ',') {
4911 protected static $libNth = ['list', 'n'];
4912 protected function libNth($args)
4914 $list = $this->coerceList($args[0]);
4915 $n = $this->assertNumber($args[1]);
4920 $n += count($list[2]);
4923 return isset($list[2][$n]) ? $list[2][$n] : static::$defaultValue;
4926 protected static $libSetNth = ['list', 'n', 'value'];
4927 protected function libSetNth($args)
4929 $list = $this->coerceList($args[0]);
4930 $n = $this->assertNumber($args[1]);
4935 $n += count($list[2]);
4938 if (! isset($list[2][$n])) {
4939 $this->throwError('Invalid argument for "n"');
4944 $list[2][$n] = $args[2];
4949 protected static $libMapGet = ['map', 'key'];
4950 protected function libMapGet($args)
4952 $map = $this->assertMap($args[0]);
4953 $key = $this->compileStringContent($this->coerceString($args[1]));
4955 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
4956 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
4961 return static::$null;
4964 protected static $libMapKeys = ['map'];
4965 protected function libMapKeys($args)
4967 $map = $this->assertMap($args[0]);
4970 return [HTML_Scss_Type::T_LIST, ',', $keys];
4973 protected static $libMapValues = ['map'];
4974 protected function libMapValues($args)
4976 $map = $this->assertMap($args[0]);
4979 return [HTML_Scss_Type::T_LIST, ',', $values];
4982 protected static $libMapRemove = ['map', 'key'];
4983 protected function libMapRemove($args)
4985 $map = $this->assertMap($args[0]);
4986 $key = $this->compileStringContent($this->coerceString($args[1]));
4988 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
4989 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
4990 array_splice($map[1], $i, 1);
4991 array_splice($map[2], $i, 1);
4998 protected static $libMapHasKey = ['map', 'key'];
4999 protected function libMapHasKey($args)
5001 $map = $this->assertMap($args[0]);
5002 $key = $this->compileStringContent($this->coerceString($args[1]));
5004 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
5005 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
5013 protected static $libMapMerge = ['map-1', 'map-2'];
5014 protected function libMapMerge($args)
5016 $map1 = $this->assertMap($args[0]);
5017 $map2 = $this->assertMap($args[1]);
5019 foreach ($map2[1] as $i2 => $key2) {
5020 $key = $this->compileStringContent($this->coerceString($key2));
5022 foreach ($map1[1] as $i1 => $key1) {
5023 if ($key === $this->compileStringContent($this->coerceString($key1))) {
5024 $map1[2][$i1] = $map2[2][$i2];
5029 $map1[1][] = $map2[1][$i2];
5030 $map1[2][] = $map2[2][$i2];
5036 protected static $libKeywords = ['args'];
5037 protected function libKeywords($args)
5039 $this->assertList($args[0]);
5044 foreach ($args[0][2] as $name => $arg) {
5045 $keys[] = [HTML_Scss_Type::T_KEYWORD, $name];
5049 return [HTML_Scss_Type::T_MAP, $keys, $values];
5052 protected function listSeparatorForJoin($list1, $sep)
5054 if (! isset($sep)) {
5058 switch ($this->compileValue($sep)) {
5070 protected static $libJoin = ['list1', 'list2', 'separator'];
5071 protected function libJoin($args)
5073 list($list1, $list2, $sep) = $args;
5075 $list1 = $this->coerceList($list1, ' ');
5076 $list2 = $this->coerceList($list2, ' ');
5077 $sep = $this->listSeparatorForJoin($list1, $sep);
5079 return [HTML_Scss_Type::T_LIST, $sep, array_merge($list1[2], $list2[2])];
5082 protected static $libAppend = ['list', 'val', 'separator'];
5083 protected function libAppend($args)
5085 list($list1, $value, $sep) = $args;
5087 $list1 = $this->coerceList($list1, ' ');
5088 $sep = $this->listSeparatorForJoin($list1, $sep);
5090 return [HTML_Scss_Type::T_LIST, $sep, array_merge($list1[2], [$value])];
5093 protected function libZip($args)
5095 foreach ($args as $arg) {
5096 $this->assertList($arg);
5100 $firstList = array_shift($args);
5102 foreach ($firstList[2] as $key => $item) {
5103 $list = [HTML_Scss_Type::T_LIST, '', [$item]];
5105 foreach ($args as $arg) {
5106 if (isset($arg[2][$key])) {
5107 $list[2][] = $arg[2][$key];
5116 return [HTML_Scss_Type::T_LIST, ',', $lists];
5119 protected static $libTypeOf = ['value'];
5120 protected function libTypeOf($args)
5124 switch ($value[0]) {
5125 case HTML_Scss_Type::T_KEYWORD:
5126 if ($value === static::$true || $value === static::$false) {
5130 if ($this->coerceColor($value)) {
5135 case HTML_Scss_Type::T_FUNCTION:
5138 case HTML_Scss_Type::T_LIST:
5139 if (isset($value[3]) && $value[3]) {
5149 protected static $libUnit = ['number'];
5150 protected function libUnit($args)
5154 if ($num[0] === HTML_Scss_Type::T_NUMBER) {
5155 return [HTML_Scss_Type::T_STRING, '"', [$num->unitStr()]];
5161 protected static $libUnitless = ['number'];
5162 protected function libUnitless($args)
5166 return $value[0] === HTML_Scss_Type::T_NUMBER && $value->unitless();
5169 protected static $libComparable = ['number-1', 'number-2'];
5170 protected function libComparable($args)
5172 list($number1, $number2) = $args;
5174 if (! isset($number1[0]) || $number1[0] !== HTML_Scss_Type::T_NUMBER ||
5175 ! isset($number2[0]) || $number2[0] !== HTML_Scss_Type::T_NUMBER
5177 $this->throwError('Invalid argument(s) for "comparable"');
5182 $number1 = $number1->normalize();
5183 $number2 = $number2->normalize();
5185 return $number1[2] === $number2[2] || $number1->unitless() || $number2->unitless();
5188 protected static $libStrIndex = ['string', 'substring'];
5189 protected function libStrIndex($args)
5191 $string = $this->coerceString($args[0]);
5192 $stringContent = $this->compileStringContent($string);
5194 $substring = $this->coerceString($args[1]);
5195 $substringContent = $this->compileStringContent($substring);
5197 $result = strpos($stringContent, $substringContent);
5199 return $result === false ? static::$null : new HTML_Scss_Node_Number($result + 1, '');
5202 protected static $libStrInsert = ['string', 'insert', 'index'];
5203 protected function libStrInsert($args)
5205 $string = $this->coerceString($args[0]);
5206 $stringContent = $this->compileStringContent($string);
5208 $insert = $this->coerceString($args[1]);
5209 $insertContent = $this->compileStringContent($insert);
5211 list(, $index) = $args[2];
5213 $string[2] = [substr_replace($stringContent, $insertContent, $index - 1, 0)];
5218 protected static $libStrLength = ['string'];
5219 protected function libStrLength($args)
5221 $string = $this->coerceString($args[0]);
5222 $stringContent = $this->compileStringContent($string);
5224 return new HTML_Scss_Node_Number(strlen($stringContent), '');
5227 protected static $libStrSlice = ['string', 'start-at', 'end-at'];
5228 protected function libStrSlice($args)
5230 if (isset($args[2]) && $args[2][1] == 0) {
5231 return static::$nullString;
5234 $string = $this->coerceString($args[0]);
5235 $stringContent = $this->compileStringContent($string);
5237 $start = (int) $args[1][1];
5243 $end = (int) $args[2][1];
5244 $length = $end < 0 ? $end + 1 : ($end > 0 ? $end - $start : $end);
5246 $string[2] = $length
5247 ? [substr($stringContent, $start, $length)]
5248 : [substr($stringContent, $start)];
5253 protected static $libToLowerCase = ['string'];
5254 protected function libToLowerCase($args)
5256 $string = $this->coerceString($args[0]);
5257 $stringContent = $this->compileStringContent($string);
5259 $string[2] = [function_exists('mb_strtolower') ? mb_strtolower($stringContent) : strtolower($stringContent)];
5264 protected static $libToUpperCase = ['string'];
5265 protected function libToUpperCase($args)
5267 $string = $this->coerceString($args[0]);
5268 $stringContent = $this->compileStringContent($string);
5270 $string[2] = [function_exists('mb_strtoupper') ? mb_strtoupper($stringContent) : strtoupper($stringContent)];
5275 protected static $libFeatureExists = ['feature'];
5276 protected function libFeatureExists($args)
5278 $string = $this->coerceString($args[0]);
5279 $name = $this->compileStringContent($string);
5281 return $this->toBool(
5282 array_key_exists($name, $this->registeredFeatures) ? $this->registeredFeatures[$name] : false
5286 protected static $libFunctionExists = ['name'];
5287 protected function libFunctionExists($args)
5289 $string = $this->coerceString($args[0]);
5290 $name = $this->compileStringContent($string);
5292 // user defined functions
5293 if ($this->has(static::$namespaces['function'] . $name)) {
5297 $name = $this->normalizeName($name);
5299 if (isset($this->userFunctions[$name])) {
5303 // built-in functions
5304 $f = $this->getBuiltinFunction($name);
5306 return $this->toBool(is_callable($f));
5309 protected static $libGlobalVariableExists = ['name'];
5310 protected function libGlobalVariableExists($args)
5312 $string = $this->coerceString($args[0]);
5313 $name = $this->compileStringContent($string);
5315 return $this->has($name, $this->rootEnv);
5318 protected static $libMixinExists = ['name'];
5319 protected function libMixinExists($args)
5321 $string = $this->coerceString($args[0]);
5322 $name = $this->compileStringContent($string);
5324 return $this->has(static::$namespaces['mixin'] . $name);
5327 protected static $libVariableExists = ['name'];
5328 protected function libVariableExists($args)
5330 $string = $this->coerceString($args[0]);
5331 $name = $this->compileStringContent($string);
5333 return $this->has($name);
5337 * Workaround IE7's content counter bug.
5339 * @param array $args
5343 protected function libCounter($args)
5345 $list = array_map([$this, 'compileValue'], $args);
5347 return [HTML_Scss_Type::T_STRING, '', ['counter(' . implode(',', $list) . ')']];
5350 protected static $libRandom = ['limit'];
5351 protected function libRandom($args)
5353 if (isset($args[0])) {
5354 $n = $this->assertNumber($args[0]);
5357 $this->throwError("limit must be greater than or equal to 1");
5362 return new HTML_Scss_Node_Number(mt_rand(1, $n), '');
5365 return new HTML_Scss_Node_Number(mt_rand(1, mt_getrandmax()), '');
5368 protected function libUniqueId()
5373 $id = mt_rand(0, pow(36, 8));
5376 $id += mt_rand(0, 10) + 1;
5378 return [HTML_Scss_Type::T_STRING, '', ['u' . str_pad(base_convert($id, 10, 36), 8, '0', STR_PAD_LEFT)]];
5381 protected static $libInspect = ['value'];
5382 protected function libInspect($args)
5384 if ($args[0] === static::$null) {
5385 return [HTML_Scss_Type::T_KEYWORD, 'null'];