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 //echo "Import file: $path\n";
3450 // see if tree is cached
3451 $realPath = realpath($path);
3453 if (isset($this->importCache[$realPath])) {
3454 $this->handleImportLoop($realPath);
3456 $tree = $this->importCache[$realPath];
3458 $code = file_get_contents($path);
3459 $parser = $this->parserFactory($path);
3460 $tree = $parser->parse($code);
3462 $this->importCache[$realPath] = $tree;
3465 $pi = pathinfo($path);
3466 array_unshift($this->importPaths, $pi['dirname']);
3467 $this->compileChildrenNoReturn($tree->children, $out);
3468 array_shift($this->importPaths);
3472 * Return the file path for an import url if it exists
3476 * @param string $url
3478 * @return string|null
3480 public function findImport($url)
3484 // for "normal" scss imports (ignore vanilla css and external requests)
3485 if (! preg_match('/\.css$|^https?:\/\//', $url)) {
3486 // try both normal and the _partial filename
3487 $urls = [$url, preg_replace('/[^\/]+$/', '_\0', $url)];
3490 $hasExtension = preg_match('/[.]s?css$/', $url);
3492 foreach ($this->importPaths as $dir) {
3493 if (is_string($dir)) {
3494 // check urls for normal import paths
3495 foreach ($urls as $full) {
3497 . (! empty($dir) && substr($dir, -1) !== '/' ? '/' : '')
3500 if ($this->fileExists($file = $full . '.scss') ||
3501 ($hasExtension && $this->fileExists($file = $full))
3506 } elseif (is_callable($dir)) {
3507 // check custom callback for import path
3508 $file = call_user_func($dir, $url);
3510 if ($file !== null) {
3524 * @param string $encoding
3526 public function setEncoding($encoding)
3528 $this->encoding = $encoding;
3536 * @param boolean $ignoreErrors
3538 * @return \Leafo\ScssPhp\Compiler
3540 public function setIgnoreErrors($ignoreErrors)
3542 $this->ignoreErrors = $ignoreErrors;
3546 * Throw error (exception)
3550 * @param string $msg Message with optional sprintf()-style vararg parameters
3552 * @throws \Leafo\ScssPhp\Exception\CompilerException
3554 public function throwError($msg)
3556 if ($this->ignoreErrors) {
3560 if (func_num_args() > 1) {
3561 $msg = call_user_func_array('sprintf', func_get_args());
3564 $line = $this->sourceLine;
3565 $msg = "$msg: line: $line";
3566 require_once 'Scss/Exception/CompilerException.php';
3567 throw new HTML_Scss_Exception_CompilerException($msg);
3571 * Handle import loop
3573 * @param string $name
3575 * @throws \Exception
3577 protected function handleImportLoop($name)
3579 for ($env = $this->env; $env; $env = $env->parent) {
3580 $file = $this->sourceNames[$env->block->sourceIndex];
3582 if (realpath($file) === $name) {
3583 $this->throwError('An @import loop has been found: %s imports %s', $file, basename($file));
3592 * @param string $name
3596 protected function fileExists($name)
3598 return file_exists($name) && is_file($name);
3602 * Call SCSS @function
3604 * @param string $name
3605 * @param array $argValues
3606 * @param array $returnValue
3608 * @return boolean Returns true if returnValue is set; otherwise, false
3610 protected function callScssFunction($name, $argValues, &$returnValue)
3612 $func = $this->get(static::$namespaces['function'] . $name, false);
3620 $storeEnv = $this->storeEnv;
3621 $this->storeEnv = $this->env;
3624 if (isset($func->args)) {
3625 $this->applyArguments($func->args, $argValues);
3628 // throw away lines and children
3629 $tmp = new HTML_Scss_Formatter_OutputBlock;
3631 $tmp->children = [];
3633 $this->env->marker = 'function';
3635 $ret = $this->compileChildren($func->children, $tmp);
3637 $this->storeEnv = $storeEnv;
3641 $returnValue = ! isset($ret) ? static::$defaultValue : $ret;
3647 * Call built-in and registered (PHP) functions
3649 * @param string $name
3650 * @param array $args
3651 * @param array $returnValue
3653 * @return boolean Returns true if returnValue is set; otherwise, false
3655 protected function callNativeFunction($name, $args, &$returnValue)
3657 // try a lib function
3658 $name = $this->normalizeName($name);
3660 if (isset($this->userFunctions[$name])) {
3661 // see if we can find a user function
3662 list($f, $prototype) = $this->userFunctions[$name];
3663 } elseif (($f = $this->getBuiltinFunction($name)) && is_callable($f)) {
3665 $prototype = isset(static::$$libName) ? static::$$libName : null;
3670 @list($sorted, $kwargs) = $this->sortArgs($prototype, $args);
3672 if ($name !== 'if' && $name !== 'call') {
3673 foreach ($sorted as &$val) {
3674 $val = $this->reduce($val, true);
3678 $returnValue = call_user_func($f, $sorted, $kwargs);
3680 if (! isset($returnValue)) {
3684 $returnValue = $this->coerceValue($returnValue);
3690 * Get built-in function
3692 * @param string $name Normalized name
3696 protected function getBuiltinFunction($name)
3698 $libName = 'lib' . preg_replace_callback(
3701 return ucfirst($m[1]);
3706 return [$this, $libName];
3710 * Sorts keyword arguments
3712 * @param array $prototype
3713 * @param array $args
3717 protected function sortArgs($prototype, $args)
3722 // separate positional and keyword arguments
3723 foreach ($args as $arg) {
3724 list($key, $value) = $arg;
3729 $posArgs[] = empty($arg[2]) ? $value : $arg;
3731 $keyArgs[$key] = $value;
3735 if (! isset($prototype)) {
3736 return [$posArgs, $keyArgs];
3739 // copy positional args
3740 $finalArgs = array_pad($posArgs, count($prototype), null);
3742 // overwrite positional args with keyword args
3743 foreach ($prototype as $i => $names) {
3744 foreach ((array) $names as $name) {
3745 if (isset($keyArgs[$name])) {
3746 $finalArgs[$i] = $keyArgs[$name];
3751 return [$finalArgs, $keyArgs];
3755 * Apply argument values per definition
3757 * @param array $argDef
3758 * @param array $argValues
3760 * @throws \Exception
3762 protected function applyArguments($argDef, $argValues)
3764 $storeEnv = $this->getStoreEnv();
3766 $env = new HTML_Scss_Compiler_Environment;
3767 $env->store = $storeEnv->store;
3769 $hasVariable = false;
3772 foreach ($argDef as $i => $arg) {
3773 list($name, $default, $isVariable) = $argDef[$i];
3775 $args[$name] = [$i, $name, $default, $isVariable];
3776 $hasVariable |= $isVariable;
3780 $deferredKeywordArgs = [];
3783 // assign the keyword args
3784 foreach ((array) $argValues as $arg) {
3785 if (! empty($arg[0])) {
3786 if (! isset($args[$arg[0][1]])) {
3788 $deferredKeywordArgs[$arg[0][1]] = $arg[1];
3790 $this->throwError("Mixin or function doesn't have an argument named $%s.", $arg[0][1]);
3793 } elseif ($args[$arg[0][1]][0] < count($remaining)) {
3794 $this->throwError("The argument $%s was passed both by position and by name.", $arg[0][1]);
3797 $keywordArgs[$arg[0][1]] = $arg[1];
3799 } elseif (count($keywordArgs)) {
3800 $this->throwError('Positional arguments must come before keyword arguments.');
3802 } elseif ($arg[2] === true) {
3803 $val = $this->reduce($arg[1], true);
3805 if ($val[0] === HTML_Scss_Type::T_LIST) {
3806 foreach ($val[2] as $name => $item) {
3807 if (! is_numeric($name)) {
3808 $keywordArgs[$name] = $item;
3810 $remaining[] = $item;
3813 } elseif ($val[0] === HTML_Scss_Type::T_MAP) {
3814 foreach ($val[1] as $i => $name) {
3815 $name = $this->compileStringContent($this->coerceString($name));
3816 $item = $val[2][$i];
3818 if (! is_numeric($name)) {
3819 $keywordArgs[$name] = $item;
3821 $remaining[] = $item;
3825 $remaining[] = $val;
3828 $remaining[] = $arg[1];
3832 foreach ($args as $arg) {
3833 list($i, $name, $default, $isVariable) = $arg;
3836 $val = [HTML_Scss_Type::T_LIST, ',', [], $isVariable];
3838 for ($count = count($remaining); $i < $count; $i++) {
3839 $val[2][] = $remaining[$i];
3842 foreach ($deferredKeywordArgs as $itemName => $item) {
3843 $val[2][$itemName] = $item;
3845 } elseif (isset($remaining[$i])) {
3846 $val = $remaining[$i];
3847 } elseif (isset($keywordArgs[$name])) {
3848 $val = $keywordArgs[$name];
3849 } elseif (! empty($default)) {
3852 $this->throwError("Missing argument $name");
3856 $this->set($name, $this->reduce($val, true), true, $env);
3859 $storeEnv->store = $env->store;
3861 foreach ($args as $arg) {
3862 list($i, $name, $default, $isVariable) = $arg;
3864 if ($isVariable || isset($remaining[$i]) || isset($keywordArgs[$name]) || empty($default)) {
3868 $this->set($name, $this->reduce($default, true), true);
3873 * Coerce a php value into a scss one
3875 * @param mixed $value
3877 * @return array|\Leafo\ScssPhp\Node\Number
3879 private function coerceValue($value)
3881 if (is_array($value) || $value instanceof ArrayAccess) {
3885 if (is_bool($value)) {
3886 return $this->toBool($value);
3889 if ($value === null) {
3890 return static::$null;
3893 if (is_numeric($value)) {
3894 return new HTML_Scss_Node_Number($value, '');
3897 if ($value === '') {
3898 return static::$emptyString;
3901 if (preg_match('/^(#([0-9a-f]{6})|#([0-9a-f]{3}))$/i', $value, $m)) {
3902 $color = [HTML_Scss_Type::T_COLOR];
3905 $num = hexdec($m[3]);
3907 foreach ([3, 2, 1] as $i) {
3909 $color[$i] = $t << 4 | $t;
3913 $num = hexdec($m[2]);
3915 foreach ([3, 2, 1] as $i) {
3916 $color[$i] = $num & 0xff;
3924 return [HTML_Scss_Type::T_KEYWORD, $value];
3928 * Coerce something to map
3930 * @param array $item
3934 protected function coerceMap($item)
3936 if ($item[0] === HTML_Scss_Type::T_MAP) {
3940 if ($item === static::$emptyList) {
3941 return static::$emptyMap;
3944 return [HTML_Scss_Type::T_MAP, [$item], [static::$null]];
3948 * Coerce something to list
3950 * @param array $item
3951 * @param string $delim
3955 protected function coerceList($item, $delim = ',')
3957 if (isset($item) && $item[0] === HTML_Scss_Type::T_LIST) {
3961 if (isset($item) && $item[0] === HTML_Scss_Type::T_MAP) {
3966 for ($i = 0, $s = count($keys); $i < $s; $i++) {
3968 $value = $values[$i];
3971 HTML_Scss_Type::T_LIST,
3973 [[HTML_Scss_Type::T_KEYWORD, $this->compileStringContent($this->coerceString($key))], $value]
3977 return [HTML_Scss_Type::T_LIST, ',', $list];
3980 return [HTML_Scss_Type::T_LIST, $delim, ! isset($item) ? []: [$item]];
3984 * Coerce color for expression
3986 * @param array $value
3988 * @return array|null
3990 protected function coerceForExpression($value)
3992 if ($color = $this->coerceColor($value)) {
4000 * Coerce value to color
4002 * @param array $value
4004 * @return array|null
4006 protected function coerceColor($value)
4008 switch ($value[0]) {
4009 case HTML_Scss_Type::T_COLOR:
4012 case HTML_Scss_Type::T_KEYWORD:
4013 $name = strtolower($value[1]);
4015 if (isset(HTML_Scss_Colors::$cssColors[$name])) {
4016 $rgba = explode(',', HTML_Scss_Colors::$cssColors[$name]);
4018 return isset($rgba[3])
4019 ? [HTML_Scss_Type::T_COLOR, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2], (int) $rgba[3]]
4020 : [HTML_Scss_Type::T_COLOR, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2]];
4030 * Coerce value to string
4032 * @param array $value
4034 * @return array|null
4036 protected function coerceString($value)
4038 if ($value[0] === HTML_Scss_Type::T_STRING) {
4042 return [HTML_Scss_Type::T_STRING, '', [$this->compileValue($value)]];
4046 * Coerce value to a percentage
4048 * @param array $value
4050 * @return integer|float
4052 protected function coercePercent($value)
4054 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4055 if (! empty($value[2]['%'])) {
4056 return $value[1] / 100;
4066 * Assert value is a map
4070 * @param array $value
4074 * @throws \Exception
4076 public function assertMap($value)
4078 $value = $this->coerceMap($value);
4080 if ($value[0] !== HTML_Scss_Type::T_MAP) {
4081 $this->throwError('expecting map');
4088 * Assert value is a list
4092 * @param array $value
4096 * @throws \Exception
4098 public function assertList($value)
4100 if ($value[0] !== HTML_Scss_Type::T_LIST) {
4101 $this->throwError('expecting list');
4108 * Assert value is a color
4112 * @param array $value
4116 * @throws \Exception
4118 public function assertColor($value)
4120 if ($color = $this->coerceColor($value)) {
4124 $this->throwError('expecting color');
4128 * Assert value is a number
4132 * @param array $value
4134 * @return integer|float
4136 * @throws \Exception
4138 public function assertNumber($value)
4140 if ($value[0] !== HTML_Scss_Type::T_NUMBER) {
4141 $this->throwError('expecting number');
4148 * Make sure a color's components don't go out of bounds
4154 protected function fixColor($c)
4156 foreach ([1, 2, 3] as $i) {
4170 * Convert RGB to HSL
4174 * @param integer $red
4175 * @param integer $green
4176 * @param integer $blue
4180 public function toHSL($red, $green, $blue)
4182 $min = min($red, $green, $blue);
4183 $max = max($red, $green, $blue);
4188 if ((int) $d === 0) {
4194 $s = $d / (510 - $l);
4198 $h = 60 * ($green - $blue) / $d;
4199 } elseif ($green == $max) {
4200 $h = 60 * ($blue - $red) / $d + 120;
4201 } elseif ($blue == $max) {
4202 $h = 60 * ($red - $green) / $d + 240;
4206 return [HTML_Scss_Type::T_HSL, fmod($h, 360), $s * 100, $l / 5.1];
4218 private function hueToRGB($m1, $m2, $h)
4227 return $m1 + ($m2 - $m1) * $h * 6;
4235 return $m1 + ($m2 - $m1) * (2/3 - $h) * 6;
4242 * Convert HSL to RGB
4246 * @param integer $hue H from 0 to 360
4247 * @param integer $saturation S from 0 to 100
4248 * @param integer $lightness L from 0 to 100
4252 public function toRGB($hue, $saturation, $lightness)
4259 $s = min(100, max(0, $saturation)) / 100;
4260 $l = min(100, max(0, $lightness)) / 100;
4262 $m2 = $l <= 0.5 ? $l * ($s + 1) : $l + $s - $l * $s;
4265 $r = $this->hueToRGB($m1, $m2, $h + 1/3) * 255;
4266 $g = $this->hueToRGB($m1, $m2, $h) * 255;
4267 $b = $this->hueToRGB($m1, $m2, $h - 1/3) * 255;
4269 $out = [HTML_Scss_Type::T_COLOR, $r, $g, $b];
4274 // Built in functions
4276 //protected static $libCall = ['name', 'args...'];
4277 protected function libCall($args, $kwargs)
4279 $name = $this->compileStringContent($this->coerceString($this->reduce(array_shift($args), true)));
4283 foreach ($args as $arg) {
4284 if (empty($arg[0])) {
4285 if ($arg[2] === true) {
4286 $tmp = $this->reduce($arg[1]);
4288 if ($tmp[0] === HTML_Scss_Type::T_LIST) {
4289 foreach ($tmp[2] as $item) {
4290 $posArgs[] = [null, $item, false];
4293 $posArgs[] = [null, $tmp, true];
4299 $posArgs[] = [null, $this->reduce($arg), false];
4303 $posArgs[] = [null, $arg, false];
4306 if (count($kwargs)) {
4307 foreach ($kwargs as $key => $value) {
4308 $posArgs[] = [[HTML_Scss_Type::T_VARIABLE, $key], $value, false];
4312 return $this->reduce([HTML_Scss_Type::T_FUNCTION_CALL, $name, $posArgs]);
4315 protected static $libIf = ['condition', 'if-true', 'if-false'];
4316 protected function libIf($args)
4318 list($cond, $t, $f) = $args;
4320 if (! $this->isTruthy($this->reduce($cond, true))) {
4321 return $this->reduce($f, true);
4324 return $this->reduce($t, true);
4327 protected static $libIndex = ['list', 'value'];
4328 protected function libIndex($args)
4330 list($list, $value) = $args;
4332 if ($value[0] === HTML_Scss_Type::T_MAP) {
4333 return static::$null;
4336 if ($list[0] === HTML_Scss_Type::T_MAP ||
4337 $list[0] === HTML_Scss_Type::T_STRING ||
4338 $list[0] === HTML_Scss_Type::T_KEYWORD ||
4339 $list[0] === HTML_Scss_Type::T_INTERPOLATE
4341 $list = $this->coerceList($list, ' ');
4344 if ($list[0] !== HTML_Scss_Type::T_LIST) {
4345 return static::$null;
4350 foreach ($list[2] as $item) {
4351 $values[] = $this->normalizeValue($item);
4354 $key = array_search($this->normalizeValue($value), $values);
4356 return false === $key ? static::$null : $key + 1;
4359 protected static $libRgb = ['red', 'green', 'blue'];
4360 protected function libRgb($args)
4362 list($r, $g, $b) = $args;
4364 return [HTML_Scss_Type::T_COLOR, $r[1], $g[1], $b[1]];
4367 protected static $libRgba = [
4369 'green', 'blue', 'alpha'];
4370 protected function libRgba($args)
4372 if ($color = $this->coerceColor($args[0])) {
4373 $num = isset($args[3]) ? $args[3] : $args[1];
4374 $alpha = $this->assertNumber($num);
4380 list($r, $g, $b, $a) = $args;
4382 return [HTML_Scss_Type::T_COLOR, $r[1], $g[1], $b[1], $a[1]];
4385 // helper function for adjust_color, change_color, and scale_color
4386 protected function alterColor($args, $fn)
4388 $color = $this->assertColor($args[0]);
4390 foreach ([1, 2, 3, 7] as $i) {
4391 if (isset($args[$i])) {
4392 $val = $this->assertNumber($args[$i]);
4393 $ii = $i === 7 ? 4 : $i; // alpha
4394 $color[$ii] = call_user_func($fn, isset($color[$ii]) ? $color[$ii] : 0, $val, $i);
4398 if (isset($args[4]) || isset($args[5]) || isset($args[6])) {
4399 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4401 foreach ([4, 5, 6] as $i) {
4402 if (isset($args[$i])) {
4403 $val = $this->assertNumber($args[$i]);
4404 $hsl[$i - 3] = call_user_func($fn, $hsl[$i - 3], $val, $i);
4408 $rgb = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
4410 if (isset($color[4])) {
4411 $rgb[4] = $color[4];
4420 protected static $libAdjustColor = [
4421 'color', 'red', 'green', 'blue',
4422 'hue', 'saturation', 'lightness', 'alpha'
4424 protected function libAdjustColor($args)
4426 return $this->alterColor($args, function ($base, $alter, $i) {
4427 return $base + $alter;
4431 protected static $libChangeColor = [
4432 'color', 'red', 'green', 'blue',
4433 'hue', 'saturation', 'lightness', 'alpha'
4435 protected function libChangeColor($args)
4437 return $this->alterColor($args, function ($base, $alter, $i) {
4442 protected static $libScaleColor = [
4443 'color', 'red', 'green', 'blue',
4444 'hue', 'saturation', 'lightness', 'alpha'
4446 protected function libScaleColor($args)
4448 return $this->alterColor($args, function ($base, $scale, $i) {
4471 $scale = $scale / 100;
4474 return $base * $scale + $base;
4477 return ($max - $base) * $scale + $base;
4481 protected static $libIeHexStr = ['color'];
4482 protected function libIeHexStr($args)
4484 $color = $this->coerceColor($args[0]);
4485 $color[4] = isset($color[4]) ? round(255 * $color[4]) : 255;
4487 return sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3]);
4490 protected static $libRed = ['color'];
4491 protected function libRed($args)
4493 $color = $this->coerceColor($args[0]);
4498 protected static $libGreen = ['color'];
4499 protected function libGreen($args)
4501 $color = $this->coerceColor($args[0]);
4506 protected static $libBlue = ['color'];
4507 protected function libBlue($args)
4509 $color = $this->coerceColor($args[0]);
4514 protected static $libAlpha = ['color'];
4515 protected function libAlpha($args)
4517 if ($color = $this->coerceColor($args[0])) {
4518 return isset($color[4]) ? $color[4] : 1;
4521 // this might be the IE function, so return value unchanged
4525 protected static $libOpacity = ['color'];
4526 protected function libOpacity($args)
4530 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4534 return $this->libAlpha($args);
4538 protected static $libMix = ['color-1', 'color-2', 'weight'];
4539 protected function libMix($args)
4541 list($first, $second, $weight) = $args;
4543 $first = $this->assertColor($first);
4544 $second = $this->assertColor($second);
4546 if (! isset($weight)) {
4549 $weight = $this->coercePercent($weight);
4552 $firstAlpha = isset($first[4]) ? $first[4] : 1;
4553 $secondAlpha = isset($second[4]) ? $second[4] : 1;
4555 $w = $weight * 2 - 1;
4556 $a = $firstAlpha - $secondAlpha;
4558 $w1 = (($w * $a === -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
4561 $new = [HTML_Scss_Type::T_COLOR,
4562 $w1 * $first[1] + $w2 * $second[1],
4563 $w1 * $first[2] + $w2 * $second[2],
4564 $w1 * $first[3] + $w2 * $second[3],
4567 if ($firstAlpha != 1.0 || $secondAlpha != 1.0) {
4568 $new[] = $firstAlpha * $weight + $secondAlpha * (1 - $weight);
4571 return $this->fixColor($new);
4574 protected static $libHsl = ['hue', 'saturation', 'lightness'];
4575 protected function libHsl($args)
4577 list($h, $s, $l) = $args;
4579 return $this->toRGB($h[1], $s[1], $l[1]);
4582 protected static $libHsla = ['hue', 'saturation', 'lightness', 'alpha'];
4583 protected function libHsla($args)
4585 list($h, $s, $l, $a) = $args;
4587 $color = $this->toRGB($h[1], $s[1], $l[1]);
4593 protected static $libHue = ['color'];
4594 protected function libHue($args)
4596 $color = $this->assertColor($args[0]);
4597 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4599 return new HTML_Scss_Node_Number($hsl[1], 'deg');
4602 protected static $libSaturation = ['color'];
4603 protected function libSaturation($args)
4605 $color = $this->assertColor($args[0]);
4606 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4608 return new HTML_Scss_Node_Number($hsl[2], '%');
4611 protected static $libLightness = ['color'];
4612 protected function libLightness($args)
4614 $color = $this->assertColor($args[0]);
4615 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4617 return new HTML_Scss_Node_Number($hsl[3], '%');
4620 protected function adjustHsl($color, $idx, $amount)
4622 $hsl = $this->toHSL($color[1], $color[2], $color[3]);
4623 $hsl[$idx] += $amount;
4624 $out = $this->toRGB($hsl[1], $hsl[2], $hsl[3]);
4626 if (isset($color[4])) {
4627 $out[4] = $color[4];
4633 protected static $libAdjustHue = ['color', 'degrees'];
4634 protected function libAdjustHue($args)
4636 $color = $this->assertColor($args[0]);
4637 $degrees = $this->assertNumber($args[1]);
4639 return $this->adjustHsl($color, 1, $degrees);
4642 protected static $libLighten = ['color', 'amount'];
4643 protected function libLighten($args)
4645 $color = $this->assertColor($args[0]);
4646 require_once 'Scss/Base/Range.php';
4647 $amount = HTML_Scss_Util::checkRange('amount', new HTML_Scss_Base_Range(0, 100), $args[1], '%');
4649 return $this->adjustHsl($color, 3, $amount);
4652 protected static $libDarken = ['color', 'amount'];
4653 protected function libDarken($args)
4655 $color = $this->assertColor($args[0]);
4656 require_once 'Scss/Base/Range.php';
4657 $amount = HTML_Scss_Util::checkRange('amount', new HTML_Scss_Base_Range(0, 100), $args[1], '%');
4659 return $this->adjustHsl($color, 3, -$amount);
4662 protected static $libSaturate = ['color', 'amount'];
4663 protected function libSaturate($args)
4667 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4671 $color = $this->assertColor($value);
4672 $amount = 100 * $this->coercePercent($args[1]);
4674 return $this->adjustHsl($color, 2, $amount);
4677 protected static $libDesaturate = ['color', 'amount'];
4678 protected function libDesaturate($args)
4680 $color = $this->assertColor($args[0]);
4681 $amount = 100 * $this->coercePercent($args[1]);
4683 return $this->adjustHsl($color, 2, -$amount);
4686 protected static $libGrayscale = ['color'];
4687 protected function libGrayscale($args)
4691 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4695 return $this->adjustHsl($this->assertColor($value), 2, -100);
4698 protected static $libComplement = ['color'];
4699 protected function libComplement($args)
4701 return $this->adjustHsl($this->assertColor($args[0]), 1, 180);
4704 protected static $libInvert = ['color'];
4705 protected function libInvert($args)
4709 if ($value[0] === HTML_Scss_Type::T_NUMBER) {
4713 $color = $this->assertColor($value);
4714 $color[1] = 255 - $color[1];
4715 $color[2] = 255 - $color[2];
4716 $color[3] = 255 - $color[3];
4721 // increases opacity by amount
4722 protected static $libOpacify = ['color', 'amount'];
4723 protected function libOpacify($args)
4725 $color = $this->assertColor($args[0]);
4726 $amount = $this->coercePercent($args[1]);
4728 $color[4] = (isset($color[4]) ? $color[4] : 1) + $amount;
4729 $color[4] = min(1, max(0, $color[4]));
4734 protected static $libFadeIn = ['color', 'amount'];
4735 protected function libFadeIn($args)
4737 return $this->libOpacify($args);
4740 // decreases opacity by amount
4741 protected static $libTransparentize = ['color', 'amount'];
4742 protected function libTransparentize($args)
4744 $color = $this->assertColor($args[0]);
4745 $amount = $this->coercePercent($args[1]);
4747 $color[4] = (isset($color[4]) ? $color[4] : 1) - $amount;
4748 $color[4] = min(1, max(0, $color[4]));
4753 protected static $libFadeOut = ['color', 'amount'];
4754 protected function libFadeOut($args)
4756 return $this->libTransparentize($args);
4759 protected static $libUnquote = ['string'];
4760 protected function libUnquote($args)
4764 if ($str[0] === HTML_Scss_Type::T_STRING) {
4771 protected static $libQuote = ['string'];
4772 protected function libQuote($args)
4776 if ($value[0] === HTML_Scss_Type::T_STRING && ! empty($value[1])) {
4780 return [HTML_Scss_Type::T_STRING, '"', [$value]];
4783 protected static $libPercentage = ['value'];
4784 protected function libPercentage($args)
4786 return new HTML_Scss_Node_Number($this->coercePercent($args[0]) * 100, '%');
4789 protected static $libRound = ['value'];
4790 protected function libRound($args)
4794 return new HTML_Scss_Node_Number(round($num[1]), $num[2]);
4797 protected static $libFloor = ['value'];
4798 protected function libFloor($args)
4802 return new HTML_Scss_Node_Number(floor($num[1]), $num[2]);
4805 protected static $libCeil = ['value'];
4806 protected function libCeil($args)
4810 return new HTML_Scss_Node_Number(ceil($num[1]), $num[2]);
4813 protected static $libAbs = ['value'];
4814 protected function libAbs($args)
4818 return new HTML_Scss_Node_Number(abs($num[1]), $num[2]);
4821 protected function libMin($args)
4823 $numbers = $this->getNormalizedNumbers($args);
4826 foreach ($numbers as $key => $number) {
4827 if (null === $min || $number[1] <= $min[1]) {
4828 $min = [$key, $number[1]];
4832 return $args[$min[0]];
4835 protected function libMax($args)
4837 $numbers = $this->getNormalizedNumbers($args);
4840 foreach ($numbers as $key => $number) {
4841 if (null === $max || $number[1] >= $max[1]) {
4842 $max = [$key, $number[1]];
4846 return $args[$max[0]];
4850 * Helper to normalize args containing numbers
4852 * @param array $args
4856 protected function getNormalizedNumbers($args)
4859 $originalUnit = null;
4862 foreach ($args as $key => $item) {
4863 if ($item[0] !== HTML_Scss_Type::T_NUMBER) {
4864 $this->throwError('%s is not a number', $item[0]);
4868 $number = $item->normalize();
4870 if (null === $unit) {
4872 $originalUnit = $item->unitStr();
4873 } elseif ($number[1] && $unit !== $number[2]) {
4874 $this->throwError('Incompatible units: "%s" and "%s".', $originalUnit, $item->unitStr());
4878 $numbers[$key] = $number;
4884 protected static $libLength = ['list'];
4885 protected function libLength($args)
4887 $list = $this->coerceList($args[0]);
4889 return count($list[2]);
4892 //protected static $libListSeparator = ['list...'];
4893 protected function libListSeparator($args)
4895 if (count($args) > 1) {
4899 $list = $this->coerceList($args[0]);
4901 if (count($list[2]) <= 1) {
4905 if ($list[1] === ',') {
4912 protected static $libNth = ['list', 'n'];
4913 protected function libNth($args)
4915 $list = $this->coerceList($args[0]);
4916 $n = $this->assertNumber($args[1]);
4921 $n += count($list[2]);
4924 return isset($list[2][$n]) ? $list[2][$n] : static::$defaultValue;
4927 protected static $libSetNth = ['list', 'n', 'value'];
4928 protected function libSetNth($args)
4930 $list = $this->coerceList($args[0]);
4931 $n = $this->assertNumber($args[1]);
4936 $n += count($list[2]);
4939 if (! isset($list[2][$n])) {
4940 $this->throwError('Invalid argument for "n"');
4945 $list[2][$n] = $args[2];
4950 protected static $libMapGet = ['map', 'key'];
4951 protected function libMapGet($args)
4953 $map = $this->assertMap($args[0]);
4954 $key = $this->compileStringContent($this->coerceString($args[1]));
4956 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
4957 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
4962 return static::$null;
4965 protected static $libMapKeys = ['map'];
4966 protected function libMapKeys($args)
4968 $map = $this->assertMap($args[0]);
4971 return [HTML_Scss_Type::T_LIST, ',', $keys];
4974 protected static $libMapValues = ['map'];
4975 protected function libMapValues($args)
4977 $map = $this->assertMap($args[0]);
4980 return [HTML_Scss_Type::T_LIST, ',', $values];
4983 protected static $libMapRemove = ['map', 'key'];
4984 protected function libMapRemove($args)
4986 $map = $this->assertMap($args[0]);
4987 $key = $this->compileStringContent($this->coerceString($args[1]));
4989 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
4990 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
4991 array_splice($map[1], $i, 1);
4992 array_splice($map[2], $i, 1);
4999 protected static $libMapHasKey = ['map', 'key'];
5000 protected function libMapHasKey($args)
5002 $map = $this->assertMap($args[0]);
5003 $key = $this->compileStringContent($this->coerceString($args[1]));
5005 for ($i = count($map[1]) - 1; $i >= 0; $i--) {
5006 if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) {
5014 protected static $libMapMerge = ['map-1', 'map-2'];
5015 protected function libMapMerge($args)
5017 $map1 = $this->assertMap($args[0]);
5018 $map2 = $this->assertMap($args[1]);
5020 foreach ($map2[1] as $i2 => $key2) {
5021 $key = $this->compileStringContent($this->coerceString($key2));
5023 foreach ($map1[1] as $i1 => $key1) {
5024 if ($key === $this->compileStringContent($this->coerceString($key1))) {
5025 $map1[2][$i1] = $map2[2][$i2];
5030 $map1[1][] = $map2[1][$i2];
5031 $map1[2][] = $map2[2][$i2];
5037 protected static $libKeywords = ['args'];
5038 protected function libKeywords($args)
5040 $this->assertList($args[0]);
5045 foreach ($args[0][2] as $name => $arg) {
5046 $keys[] = [HTML_Scss_Type::T_KEYWORD, $name];
5050 return [HTML_Scss_Type::T_MAP, $keys, $values];
5053 protected function listSeparatorForJoin($list1, $sep)
5055 if (! isset($sep)) {
5059 switch ($this->compileValue($sep)) {
5071 protected static $libJoin = ['list1', 'list2', 'separator'];
5072 protected function libJoin($args)
5074 list($list1, $list2, $sep) = $args;
5076 $list1 = $this->coerceList($list1, ' ');
5077 $list2 = $this->coerceList($list2, ' ');
5078 $sep = $this->listSeparatorForJoin($list1, $sep);
5080 return [HTML_Scss_Type::T_LIST, $sep, array_merge($list1[2], $list2[2])];
5083 protected static $libAppend = ['list', 'val', 'separator'];
5084 protected function libAppend($args)
5086 list($list1, $value, $sep) = $args;
5088 $list1 = $this->coerceList($list1, ' ');
5089 $sep = $this->listSeparatorForJoin($list1, $sep);
5091 return [HTML_Scss_Type::T_LIST, $sep, array_merge($list1[2], [$value])];
5094 protected function libZip($args)
5096 foreach ($args as $arg) {
5097 $this->assertList($arg);
5101 $firstList = array_shift($args);
5103 foreach ($firstList[2] as $key => $item) {
5104 $list = [HTML_Scss_Type::T_LIST, '', [$item]];
5106 foreach ($args as $arg) {
5107 if (isset($arg[2][$key])) {
5108 $list[2][] = $arg[2][$key];
5117 return [HTML_Scss_Type::T_LIST, ',', $lists];
5120 protected static $libTypeOf = ['value'];
5121 protected function libTypeOf($args)
5125 switch ($value[0]) {
5126 case HTML_Scss_Type::T_KEYWORD:
5127 if ($value === static::$true || $value === static::$false) {
5131 if ($this->coerceColor($value)) {
5136 case HTML_Scss_Type::T_FUNCTION:
5139 case HTML_Scss_Type::T_LIST:
5140 if (isset($value[3]) && $value[3]) {
5150 protected static $libUnit = ['number'];
5151 protected function libUnit($args)
5155 if ($num[0] === HTML_Scss_Type::T_NUMBER) {
5156 return [HTML_Scss_Type::T_STRING, '"', [$num->unitStr()]];
5162 protected static $libUnitless = ['number'];
5163 protected function libUnitless($args)
5167 return $value[0] === HTML_Scss_Type::T_NUMBER && $value->unitless();
5170 protected static $libComparable = ['number-1', 'number-2'];
5171 protected function libComparable($args)
5173 list($number1, $number2) = $args;
5175 if (! isset($number1[0]) || $number1[0] !== HTML_Scss_Type::T_NUMBER ||
5176 ! isset($number2[0]) || $number2[0] !== HTML_Scss_Type::T_NUMBER
5178 $this->throwError('Invalid argument(s) for "comparable"');
5183 $number1 = $number1->normalize();
5184 $number2 = $number2->normalize();
5186 return $number1[2] === $number2[2] || $number1->unitless() || $number2->unitless();
5189 protected static $libStrIndex = ['string', 'substring'];
5190 protected function libStrIndex($args)
5192 $string = $this->coerceString($args[0]);
5193 $stringContent = $this->compileStringContent($string);
5195 $substring = $this->coerceString($args[1]);
5196 $substringContent = $this->compileStringContent($substring);
5198 $result = strpos($stringContent, $substringContent);
5200 return $result === false ? static::$null : new HTML_Scss_Node_Number($result + 1, '');
5203 protected static $libStrInsert = ['string', 'insert', 'index'];
5204 protected function libStrInsert($args)
5206 $string = $this->coerceString($args[0]);
5207 $stringContent = $this->compileStringContent($string);
5209 $insert = $this->coerceString($args[1]);
5210 $insertContent = $this->compileStringContent($insert);
5212 list(, $index) = $args[2];
5214 $string[2] = [substr_replace($stringContent, $insertContent, $index - 1, 0)];
5219 protected static $libStrLength = ['string'];
5220 protected function libStrLength($args)
5222 $string = $this->coerceString($args[0]);
5223 $stringContent = $this->compileStringContent($string);
5225 return new HTML_Scss_Node_Number(strlen($stringContent), '');
5228 protected static $libStrSlice = ['string', 'start-at', 'end-at'];
5229 protected function libStrSlice($args)
5231 if (isset($args[2]) && $args[2][1] == 0) {
5232 return static::$nullString;
5235 $string = $this->coerceString($args[0]);
5236 $stringContent = $this->compileStringContent($string);
5238 $start = (int) $args[1][1];
5244 $end = (int) isset($args[2][1]) ? $args[2][1] : 0;
5245 $length = $end < 0 ? $end + 1 : ($end > 0 ? $end - $start : $end);
5247 $string[2] = $length
5248 ? [substr($stringContent, $start, $length)]
5249 : [substr($stringContent, $start)];
5254 protected static $libToLowerCase = ['string'];
5255 protected function libToLowerCase($args)
5257 $string = $this->coerceString($args[0]);
5258 $stringContent = $this->compileStringContent($string);
5260 $string[2] = [function_exists('mb_strtolower') ? mb_strtolower($stringContent) : strtolower($stringContent)];
5265 protected static $libToUpperCase = ['string'];
5266 protected function libToUpperCase($args)
5268 $string = $this->coerceString($args[0]);
5269 $stringContent = $this->compileStringContent($string);
5271 $string[2] = [function_exists('mb_strtoupper') ? mb_strtoupper($stringContent) : strtoupper($stringContent)];
5276 protected static $libFeatureExists = ['feature'];
5277 protected function libFeatureExists($args)
5279 $string = $this->coerceString($args[0]);
5280 $name = $this->compileStringContent($string);
5282 return $this->toBool(
5283 array_key_exists($name, $this->registeredFeatures) ? $this->registeredFeatures[$name] : false
5287 protected static $libFunctionExists = ['name'];
5288 protected function libFunctionExists($args)
5290 $string = $this->coerceString($args[0]);
5291 $name = $this->compileStringContent($string);
5293 // user defined functions
5294 if ($this->has(static::$namespaces['function'] . $name)) {
5298 $name = $this->normalizeName($name);
5300 if (isset($this->userFunctions[$name])) {
5304 // built-in functions
5305 $f = $this->getBuiltinFunction($name);
5307 return $this->toBool(is_callable($f));
5310 protected static $libGlobalVariableExists = ['name'];
5311 protected function libGlobalVariableExists($args)
5313 $string = $this->coerceString($args[0]);
5314 $name = $this->compileStringContent($string);
5316 return $this->has($name, $this->rootEnv);
5319 protected static $libMixinExists = ['name'];
5320 protected function libMixinExists($args)
5322 $string = $this->coerceString($args[0]);
5323 $name = $this->compileStringContent($string);
5325 return $this->has(static::$namespaces['mixin'] . $name);
5328 protected static $libVariableExists = ['name'];
5329 protected function libVariableExists($args)
5331 $string = $this->coerceString($args[0]);
5332 $name = $this->compileStringContent($string);
5334 return $this->has($name);
5338 * Workaround IE7's content counter bug.
5340 * @param array $args
5344 protected function libCounter($args)
5346 $list = array_map([$this, 'compileValue'], $args);
5348 return [HTML_Scss_Type::T_STRING, '', ['counter(' . implode(',', $list) . ')']];
5351 protected static $libRandom = ['limit'];
5352 protected function libRandom($args)
5354 if (isset($args[0])) {
5355 $n = $this->assertNumber($args[0]);
5358 $this->throwError("limit must be greater than or equal to 1");
5363 return new HTML_Scss_Node_Number(mt_rand(1, $n), '');
5366 return new HTML_Scss_Node_Number(mt_rand(1, mt_getrandmax()), '');
5369 protected function libUniqueId()
5374 $id = mt_rand(0, pow(36, 8));
5377 $id += mt_rand(0, 10) + 1;
5379 return [HTML_Scss_Type::T_STRING, '', ['u' . str_pad(base_convert($id, 10, 36), 8, '0', STR_PAD_LEFT)]];
5382 protected static $libInspect = ['value'];
5383 protected function libInspect($args)
5385 if ($args[0] === static::$null) {
5386 return [HTML_Scss_Type::T_KEYWORD, 'null'];