diff --git a/composer.json b/composer.json index 7e2f27b43..5a284a28b 100644 --- a/composer.json +++ b/composer.json @@ -36,7 +36,7 @@ "pimple/pimple": "3.2.3", "punic/punic": "^1.6", "sabre/dav": "^4.0.0", - "scssphp/scssphp": "1.0.3", + "scssphp/scssphp": "1.1.1", "stecman/symfony-console-completion": "^0.11.0", "swiftmailer/swiftmailer": "^6.0", "symfony/console": "4.4.4", diff --git a/composer.lock b/composer.lock index cc4ace864..b60eca30a 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "bd221adad98a16b0a54fcfc12cbb6f49", + "content-hash": "abfd697e61178f08cc5f116cd5c99df9", "packages": [ { "name": "aws/aws-sdk-php", @@ -473,20 +473,6 @@ "redis", "xcache" ], - "funding": [ - { - "url": "https://www.doctrine-project.org/sponsorship.html", - "type": "custom" - }, - { - "url": "https://www.patreon.com/phpdoctrine", - "type": "patreon" - }, - { - "url": "https://tidelift.com/funding/github/packagist/doctrine%2Fcache", - "type": "tidelift" - } - ], "time": "2020-05-27T16:24:54+00:00" }, { @@ -729,20 +715,6 @@ "sqlserver", "sqlsrv" ], - "funding": [ - { - "url": "https://www.doctrine-project.org/sponsorship.html", - "type": "custom" - }, - { - "url": "https://www.patreon.com/phpdoctrine", - "type": "patreon" - }, - { - "url": "https://tidelift.com/funding/github/packagist/doctrine%2Fdbal", - "type": "tidelift" - } - ], "time": "2020-04-20T17:19:26+00:00" }, { @@ -1661,7 +1633,7 @@ "time": "2015-08-01T16:27:37+00:00" }, { - "name": "jeremeamia/SuperClosure", + "name": "jeremeamia/superclosure", "version": "2.4.0", "source": { "type": "git", @@ -3915,24 +3887,26 @@ }, { "name": "scssphp/scssphp", - "version": "1.0.3", + "version": "1.1.1", "source": { "type": "git", "url": "https://github.com/scssphp/scssphp.git", - "reference": "616c518333c656eaa23182ac6cfc01453f1e7c78" + "reference": "824e4cec10b2bfa88eec5dac23991cb9106622c1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/scssphp/scssphp/zipball/616c518333c656eaa23182ac6cfc01453f1e7c78", - "reference": "616c518333c656eaa23182ac6cfc01453f1e7c78", + "url": "https://api.github.com/repos/scssphp/scssphp/zipball/824e4cec10b2bfa88eec5dac23991cb9106622c1", + "reference": "824e4cec10b2bfa88eec5dac23991cb9106622c1", "shasum": "" }, "require": { - "php": "^5.6.0 || ^7" + "ext-ctype": "*", + "ext-json": "*", + "php": ">=5.6.0" }, "require-dev": { - "phpunit/phpunit": "~4.6", - "squizlabs/php_codesniffer": "~2.5", + "phpunit/phpunit": "^5.7 || ^6.5 || ^7.5 || ^8.3", + "squizlabs/php_codesniffer": "~3.5", "twbs/bootstrap": "~4.3", "zurb/foundation": "~6.5" }, @@ -3970,7 +3944,7 @@ "scss", "stylesheet" ], - "time": "2019-08-07T20:16:04+00:00" + "time": "2020-06-04T17:30:40+00:00" }, { "name": "spomky-labs/base64url", @@ -5388,6 +5362,5 @@ "platform-dev": [], "platform-overrides": { "php": "7.2.0" - }, - "plugin-api-version": "1.1.0" + } } diff --git a/composer/autoload_classmap.php b/composer/autoload_classmap.php index e70c0dc82..563c968f1 100644 --- a/composer/autoload_classmap.php +++ b/composer/autoload_classmap.php @@ -2505,7 +2505,6 @@ 'ScssPhp\\ScssPhp\\Parser' => $vendorDir . '/scssphp/scssphp/src/Parser.php', 'ScssPhp\\ScssPhp\\SourceMap\\Base64' => $vendorDir . '/scssphp/scssphp/src/SourceMap/Base64.php', 'ScssPhp\\ScssPhp\\SourceMap\\Base64VLQ' => $vendorDir . '/scssphp/scssphp/src/SourceMap/Base64VLQ.php', - 'ScssPhp\\ScssPhp\\SourceMap\\Base64VLQEncoder' => $vendorDir . '/scssphp/scssphp/src/SourceMap/Base64VLQEncoder.php', 'ScssPhp\\ScssPhp\\SourceMap\\SourceMapGenerator' => $vendorDir . '/scssphp/scssphp/src/SourceMap/SourceMapGenerator.php', 'ScssPhp\\ScssPhp\\Type' => $vendorDir . '/scssphp/scssphp/src/Type.php', 'ScssPhp\\ScssPhp\\Util' => $vendorDir . '/scssphp/scssphp/src/Util.php', diff --git a/composer/autoload_static.php b/composer/autoload_static.php index d1a75043a..3d7ee6c8c 100644 --- a/composer/autoload_static.php +++ b/composer/autoload_static.php @@ -3025,7 +3025,6 @@ class ComposerStaticInit2f23f73bc0cc116b4b1eee1521aa8652 'ScssPhp\\ScssPhp\\Parser' => __DIR__ . '/..' . '/scssphp/scssphp/src/Parser.php', 'ScssPhp\\ScssPhp\\SourceMap\\Base64' => __DIR__ . '/..' . '/scssphp/scssphp/src/SourceMap/Base64.php', 'ScssPhp\\ScssPhp\\SourceMap\\Base64VLQ' => __DIR__ . '/..' . '/scssphp/scssphp/src/SourceMap/Base64VLQ.php', - 'ScssPhp\\ScssPhp\\SourceMap\\Base64VLQEncoder' => __DIR__ . '/..' . '/scssphp/scssphp/src/SourceMap/Base64VLQEncoder.php', 'ScssPhp\\ScssPhp\\SourceMap\\SourceMapGenerator' => __DIR__ . '/..' . '/scssphp/scssphp/src/SourceMap/SourceMapGenerator.php', 'ScssPhp\\ScssPhp\\Type' => __DIR__ . '/..' . '/scssphp/scssphp/src/Type.php', 'ScssPhp\\ScssPhp\\Util' => __DIR__ . '/..' . '/scssphp/scssphp/src/Util.php', diff --git a/composer/installed.json b/composer/installed.json index 3fb52f0df..d78d9fef1 100644 --- a/composer/installed.json +++ b/composer/installed.json @@ -4036,29 +4036,31 @@ }, { "name": "scssphp/scssphp", - "version": "1.0.3", - "version_normalized": "1.0.3.0", + "version": "1.1.1", + "version_normalized": "1.1.1.0", "source": { "type": "git", "url": "https://github.com/scssphp/scssphp.git", - "reference": "616c518333c656eaa23182ac6cfc01453f1e7c78" + "reference": "824e4cec10b2bfa88eec5dac23991cb9106622c1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/scssphp/scssphp/zipball/616c518333c656eaa23182ac6cfc01453f1e7c78", - "reference": "616c518333c656eaa23182ac6cfc01453f1e7c78", + "url": "https://api.github.com/repos/scssphp/scssphp/zipball/824e4cec10b2bfa88eec5dac23991cb9106622c1", + "reference": "824e4cec10b2bfa88eec5dac23991cb9106622c1", "shasum": "" }, "require": { - "php": "^5.6.0 || ^7" + "ext-ctype": "*", + "ext-json": "*", + "php": ">=5.6.0" }, "require-dev": { - "phpunit/phpunit": "~4.6", - "squizlabs/php_codesniffer": "~2.5", + "phpunit/phpunit": "^5.7 || ^6.5 || ^7.5 || ^8.3", + "squizlabs/php_codesniffer": "~3.5", "twbs/bootstrap": "~4.3", "zurb/foundation": "~6.5" }, - "time": "2019-08-07T20:16:04+00:00", + "time": "2020-06-04T17:30:40+00:00", "bin": [ "bin/pscss" ], diff --git a/scssphp/scssphp/README.md b/scssphp/scssphp/README.md index f541e4888..86eba25ca 100644 --- a/scssphp/scssphp/README.md +++ b/scssphp/scssphp/README.md @@ -24,7 +24,6 @@ There are several tests in the `tests/` directory: * `InputTest.php` compiles every `.scss` file in the `tests/inputs` directory then compares to the respective `.css` file in the `tests/outputs` directory. * `ScssTest.php` extracts (ruby) `scss` tests from the `tests/scss_test.rb` file. -* `ServerTest.php` contains functional tests for the `Server` class. When changing any of the tests in `tests/inputs`, the tests will most likely fail because the output has changed. Once you verify that the output is correct diff --git a/scssphp/scssphp/composer.json b/scssphp/scssphp/composer.json index cbeb96578..43f556537 100644 --- a/scssphp/scssphp/composer.json +++ b/scssphp/scssphp/composer.json @@ -23,17 +23,20 @@ "psr-4": { "ScssPhp\\ScssPhp\\": "src/" } }, "autoload-dev": { - "psr-4": { "ScssPhp\\ScssPhp\\Test\\": "tests/" } + "psr-4": { "ScssPhp\\ScssPhp\\Tests\\": "tests/" } }, "require": { - "php": "^5.6.0 || ^7" + "php": ">=5.6.0", + "ext-json": "*", + "ext-ctype": "*" }, "require-dev": { - "squizlabs/php_codesniffer": "~2.5", - "phpunit/phpunit": "~4.6", + "squizlabs/php_codesniffer": "~3.5", + "phpunit/phpunit": "^5.7 || ^6.5 || ^7.5 || ^8.3", "twbs/bootstrap": "~4.3", "zurb/foundation": "~6.5" }, + "minimum-stability": "dev", "bin": ["bin/pscss"], "archive": { "exclude": [ diff --git a/scssphp/scssphp/src/Base/Range.php b/scssphp/scssphp/src/Base/Range.php index 094e90303..e269ebf10 100644 --- a/scssphp/scssphp/src/Base/Range.php +++ b/scssphp/scssphp/src/Base/Range.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2015-2019 Leaf Corcoran + * @copyright 2015-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Block.php b/scssphp/scssphp/src/Block.php index bb1afdd4b..eb073c553 100644 --- a/scssphp/scssphp/src/Block.php +++ b/scssphp/scssphp/src/Block.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Cache.php b/scssphp/scssphp/src/Cache.php index 1cf496f51..91a2d7486 100644 --- a/scssphp/scssphp/src/Cache.php +++ b/scssphp/scssphp/src/Cache.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -22,13 +22,12 @@ * taking in account options that affects the result * * The cache manager is agnostic about data format and only the operation is expected to be described by string - * */ /** * SCSS cache * - * @author Cedric Morin + * @author Cedric Morin */ class Cache { @@ -57,12 +56,12 @@ class Cache public function __construct($options) { // check $cacheDir - if (isset($options['cache_dir'])) { - self::$cacheDir = $options['cache_dir']; + if (isset($options['cacheDir'])) { + self::$cacheDir = $options['cacheDir']; } if (empty(self::$cacheDir)) { - throw new Exception('cache_dir not set'); + throw new Exception('cacheDir not set'); } if (isset($options['prefix'])) { @@ -74,7 +73,7 @@ public function __construct($options) } if (isset($options['forceRefresh'])) { - self::$forceRefresh = $options['force_refresh']; + self::$forceRefresh = $options['forceRefresh']; } self::checkCacheDir(); @@ -97,18 +96,18 @@ public function getCache($operation, $what, $options = [], $lastModified = null) { $fileCache = self::$cacheDir . self::cacheName($operation, $what, $options); - if ((! self::$forceRefresh || (self::$forceRefresh === 'once' && + if (((self::$forceRefresh === false) || (self::$forceRefresh === 'once' && isset(self::$refreshed[$fileCache]))) && file_exists($fileCache) ) { $cacheTime = filemtime($fileCache); - if ((is_null($lastModified) || $cacheTime > $lastModified) && + if ((\is_null($lastModified) || $cacheTime > $lastModified) && $cacheTime + self::$gcLifetime > time() ) { $c = file_get_contents($fileCache); $c = unserialize($c); - if (is_array($c) && isset($c['value'])) { + if (\is_array($c) && isset($c['value'])) { return $c['value']; } } @@ -132,6 +131,7 @@ public function setCache($operation, $what, $value, $options = []) $c = ['value' => $value]; $c = serialize($c); + file_put_contents($fileCache, $c); if (self::$forceRefresh === 'once') { @@ -176,13 +176,13 @@ public static function checkCacheDir() self::$cacheDir = str_replace('\\', '/', self::$cacheDir); self::$cacheDir = rtrim(self::$cacheDir, '/') . '/'; - if (! file_exists(self::$cacheDir)) { + if (! is_dir(self::$cacheDir)) { if (! mkdir(self::$cacheDir)) { throw new Exception('Cache directory couldn\'t be created: ' . self::$cacheDir); } - } elseif (! is_dir(self::$cacheDir)) { - throw new Exception('Cache directory doesn\'t exist: ' . self::$cacheDir); - } elseif (! is_writable(self::$cacheDir)) { + } + + if (! is_writable(self::$cacheDir)) { throw new Exception('Cache directory isn\'t writable: ' . self::$cacheDir); } } diff --git a/scssphp/scssphp/src/Colors.php b/scssphp/scssphp/src/Colors.php index ad459246a..c3ca1bfb2 100644 --- a/scssphp/scssphp/src/Colors.php +++ b/scssphp/scssphp/src/Colors.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -25,7 +25,7 @@ class Colors * * @var array */ - public static $cssColors = [ + protected static $cssColors = [ 'aliceblue' => '240,248,255', 'antiquewhite' => '250,235,215', 'aqua' => '0,255,255', @@ -176,4 +176,66 @@ class Colors 'yellow' => '255,255,0', 'yellowgreen' => '154,205,50', ]; + + /** + * Convert named color in a [r,g,b[,a]] array + * + * @param string $colorName + * + * @return array|null + */ + public static function colorNameToRGBa($colorName) + { + if (\is_string($colorName) && isset(static::$cssColors[$colorName])) { + $rgba = explode(',', static::$cssColors[$colorName]); + + // only case with opacity is transparent, with opacity=0, so we can intval on opacity also + $rgba = array_map('intval', $rgba); + + return $rgba; + } + + return null; + } + + /** + * Reverse conversion : from RGBA to a color name if possible + * + * @param integer $r + * @param integer $g + * @param integer $b + * @param integer $a + * + * @return string|null + */ + public static function RGBaToColorName($r, $g, $b, $a = 1) + { + static $reverseColorTable = null; + + if (! is_numeric($r) || ! is_numeric($g) || ! is_numeric($b) || ! is_numeric($a)) { + return null; + } + + if ($a < 1) { + return null; + } + + if (\is_null($reverseColorTable)) { + $reverseColorTable = []; + + foreach (static::$cssColors as $name => $rgb_str) { + $rgb_str = explode(',', $rgb_str); + + if (\count($rgb_str) == 3) { + $reverseColorTable[\intval($rgb_str[0])][\intval($rgb_str[1])][\intval($rgb_str[2])] = $name; + } + } + } + + if (isset($reverseColorTable[\intval($r)][\intval($g)][\intval($b)])) { + return $reverseColorTable[\intval($r)][\intval($g)][\intval($b)]; + } + + return null; + } } diff --git a/scssphp/scssphp/src/Compiler.php b/scssphp/scssphp/src/Compiler.php index 6e4b729ec..eef6970a6 100644 --- a/scssphp/scssphp/src/Compiler.php +++ b/scssphp/scssphp/src/Compiler.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -73,7 +73,7 @@ class Compiler /** * @var array */ - static protected $operatorNames = [ + protected static $operatorNames = [ '+' => 'add', '-' => 'sub', '*' => 'mul', @@ -93,23 +93,25 @@ class Compiler /** * @var array */ - static protected $namespaces = [ + protected static $namespaces = [ 'special' => '%', 'mixin' => '@', 'function' => '^', ]; - static public $true = [Type::T_KEYWORD, 'true']; - static public $false = [Type::T_KEYWORD, 'false']; - static public $null = [Type::T_NULL]; - static public $nullString = [Type::T_STRING, '', []]; - static public $defaultValue = [Type::T_KEYWORD, '']; - static public $selfSelector = [Type::T_SELF]; - static public $emptyList = [Type::T_LIST, '', []]; - static public $emptyMap = [Type::T_MAP, [], []]; - static public $emptyString = [Type::T_STRING, '"', []]; - static public $with = [Type::T_KEYWORD, 'with']; - static public $without = [Type::T_KEYWORD, 'without']; + public static $true = [Type::T_KEYWORD, 'true']; + public static $false = [Type::T_KEYWORD, 'false']; + public static $NaN = [Type::T_KEYWORD, 'NaN']; + public static $Infinity = [Type::T_KEYWORD, 'Infinity']; + public static $null = [Type::T_NULL]; + public static $nullString = [Type::T_STRING, '', []]; + public static $defaultValue = [Type::T_KEYWORD, '']; + public static $selfSelector = [Type::T_SELF]; + public static $emptyList = [Type::T_LIST, '', []]; + public static $emptyMap = [Type::T_MAP, [], []]; + public static $emptyString = [Type::T_STRING, '"', []]; + public static $with = [Type::T_KEYWORD, 'with']; + public static $without = [Type::T_KEYWORD, 'without']; protected $importPaths = ['']; protected $importCache = []; @@ -159,11 +161,14 @@ class Compiler protected $stderr; protected $shouldEvaluate; protected $ignoreErrors; + protected $ignoreCallStackMessage = false; protected $callStack = []; /** * Constructor + * + * @param array|null $cacheOptions */ public function __construct($cacheOptions = null) { @@ -173,8 +178,15 @@ public function __construct($cacheOptions = null) if ($cacheOptions) { $this->cache = new Cache($cacheOptions); } + + $this->stderr = fopen('php://stderr', 'w'); } + /** + * Get compiler options + * + * @return array + */ public function getCompileOptions() { $options = [ @@ -190,6 +202,16 @@ public function getCompileOptions() return $options; } + /** + * Set an alternative error output stream, for testing purpose only + * + * @param resource $handle + */ + public function setErrorOuput($handle) + { + $this->stderr = $handle; + } + /** * Compile scss * @@ -207,10 +229,10 @@ public function compile($code, $path = null) $compileOptions = $this->getCompileOptions(); $cache = $this->cache->getCache("compile", $cacheKey, $compileOptions); - if (is_array($cache) && isset($cache['dependencies']) && isset($cache['out'])) { + if (\is_array($cache) && isset($cache['dependencies']) && isset($cache['out'])) { // check if any dependency file changed before accepting the cache foreach ($cache['dependencies'] as $file => $mtime) { - if (! file_exists($file) || filemtime($file) !== $mtime) { + if (! is_file($file) || filemtime($file) !== $mtime) { unset($cache); break; } @@ -234,7 +256,7 @@ public function compile($code, $path = null) $this->storeEnv = null; $this->charsetSeen = null; $this->shouldEvaluate = null; - $this->stderr = fopen('php://stderr', 'w'); + $this->ignoreCallStackMessage = false; $this->parser = $this->parserFactory($path); $tree = $this->parser->parse($code); @@ -251,7 +273,7 @@ public function compile($code, $path = null) $sourceMapGenerator = null; if ($this->sourceMap) { - if (is_object($this->sourceMap) && $this->sourceMap instanceof SourceMapGenerator) { + if (\is_object($this->sourceMap) && $this->sourceMap instanceof SourceMapGenerator) { $sourceMapGenerator = $this->sourceMap; $this->sourceMap = self::SOURCE_MAP_FILE; } elseif ($this->sourceMap !== self::SOURCE_MAP_NONE) { @@ -299,7 +321,18 @@ public function compile($code, $path = null) */ protected function parserFactory($path) { - $parser = new Parser($path, count($this->sourceNames), $this->encoding, $this->cache); + // https://sass-lang.com/documentation/at-rules/import + // CSS files imported by Sass don’t allow any special Sass features. + // In order to make sure authors don’t accidentally write Sass in their CSS, + // all Sass features that aren’t also valid CSS will produce errors. + // Otherwise, the CSS will be rendered as-is. It can even be extended! + $cssOnly = false; + + if (substr($path, '-4') === '.css') { + $cssOnly = true; + } + + $parser = new Parser($path, \count($this->sourceNames), $this->encoding, $this->cache, $cssOnly); $this->sourceNames[] = $path; $this->addParsedFile($path); @@ -318,7 +351,7 @@ protected function parserFactory($path) protected function isSelfExtend($target, $origin) { foreach ($origin as $sel) { - if (in_array($target, $sel)) { + if (\in_array($target, $sel)) { return true; } } @@ -329,17 +362,13 @@ protected function isSelfExtend($target, $origin) /** * Push extends * - * @param array $target - * @param array $origin - * @param \stdClass $block + * @param array $target + * @param array $origin + * @param array|null $block */ protected function pushExtends($target, $origin, $block) { - if ($this->isSelfExtend($target, $origin)) { - return; - } - - $i = count($this->extends); + $i = \count($this->extends); $this->extends[] = [$target, $origin, $block]; foreach ($target as $part) { @@ -362,12 +391,12 @@ protected function pushExtends($target, $origin, $block) protected function makeOutputBlock($type, $selectors = null) { $out = new OutputBlock; - $out->type = $type; - $out->lines = []; - $out->children = []; - $out->parent = $this->scope; - $out->selectors = $selectors; - $out->depth = $this->env->depth; + $out->type = $type; + $out->lines = []; + $out->children = []; + $out->parent = $this->scope; + $out->selectors = $selectors; + $out->depth = $this->env->depth; if ($this->env->block instanceof Block) { $out->sourceName = $this->env->block->sourceName; @@ -435,7 +464,7 @@ protected function flattenSelectors(OutputBlock $block, $parentKey = null) foreach ($block->selectors as $s) { $selectors[] = $s; - if (! is_array($s)) { + if (! \is_array($s)) { continue; } @@ -468,7 +497,7 @@ protected function flattenSelectors(OutputBlock $block, $parentKey = null) $block->selectors[] = $this->compileSelector($selector); } - if ($placeholderSelector && 0 === count($block->selectors) && null !== $parentKey) { + if ($placeholderSelector && 0 === \count($block->selectors) && null !== $parentKey) { unset($block->parent->children[$parentKey]); return; @@ -492,16 +521,19 @@ protected function glueFunctionSelectors($parts) $new = []; foreach ($parts as $part) { - if (is_array($part)) { + if (\is_array($part)) { $part = $this->glueFunctionSelectors($part); $new[] = $part; } else { // a selector part finishing with a ) is the last part of a :not( or :nth-child( // and need to be joined to this - if (count($new) && is_string($new[count($new) - 1]) && - strlen($part) && substr($part, -1) === ')' && strpos($part, '(') === false + if (\count($new) && \is_string($new[\count($new) - 1]) && + \strlen($part) && substr($part, -1) === ')' && strpos($part, '(') === false ) { - $new[count($new) - 1] .= $part; + while (\count($new)>1 && substr($new[\count($new) - 1], -1) !== '(') { + $part = array_pop($new) . $part; + } + $new[\count($new) - 1] .= $part; } else { $new[] = $part; } @@ -522,13 +554,14 @@ protected function glueFunctionSelectors($parts) protected function matchExtends($selector, &$out, $from = 0, $initial = true) { static $partsPile = []; - $selector = $this->glueFunctionSelectors($selector); - if (count($selector) == 1 && in_array(reset($selector), $partsPile)) { + if (\count($selector) == 1 && \in_array(reset($selector), $partsPile)) { return; } + $outRecurs = []; + foreach ($selector as $i => $part) { if ($i < $from) { continue; @@ -536,39 +569,43 @@ protected function matchExtends($selector, &$out, $from = 0, $initial = true) // check that we are not building an infinite loop of extensions // if the new part is just including a previous part don't try to extend anymore - if (count($part) > 1) { + if (\count($part) > 1) { foreach ($partsPile as $previousPart) { - if (! count(array_diff($previousPart, $part))) { + if (! \count(array_diff($previousPart, $part))) { continue 2; } } } - if ($this->matchExtendsSingle($part, $origin)) { - $partsPile[] = $part; - $after = array_slice($selector, $i + 1); - $before = array_slice($selector, 0, $i); + $partsPile[] = $part; + if ($this->matchExtendsSingle($part, $origin, $initial)) { + $after = \array_slice($selector, $i + 1); + $before = \array_slice($selector, 0, $i); list($before, $nonBreakableBefore) = $this->extractRelationshipFromFragment($before); foreach ($origin as $new) { $k = 0; // remove shared parts - if (count($new) > 1) { + if (\count($new) > 1) { while ($k < $i && isset($new[$k]) && $selector[$k] === $new[$k]) { $k++; } } + if (\count($nonBreakableBefore) and $k == \count($new)) { + $k--; + } + $replacement = []; - $tempReplacement = $k > 0 ? array_slice($new, $k) : $new; + $tempReplacement = $k > 0 ? \array_slice($new, $k) : $new; - for ($l = count($tempReplacement) - 1; $l >= 0; $l--) { + for ($l = \count($tempReplacement) - 1; $l >= 0; $l--) { $slice = []; foreach ($tempReplacement[$l] as $chunk) { - if (! in_array($chunk, $slice)) { + if (! \in_array($chunk, $slice)) { $slice[] = $chunk; } } @@ -580,7 +617,7 @@ protected function matchExtends($selector, &$out, $from = 0, $initial = true) } } - $afterBefore = $l != 0 ? array_slice($tempReplacement, 0, $l) : []; + $afterBefore = $l != 0 ? \array_slice($tempReplacement, 0, $l) : []; // Merge shared direct relationships. $mergedBefore = $this->mergeDirectRelationships($afterBefore, $nonBreakableBefore); @@ -596,64 +633,134 @@ protected function matchExtends($selector, &$out, $from = 0, $initial = true) continue; } - $out[] = $result; + $this->pushOrMergeExtentedSelector($out, $result); // recursively check for more matches - $startRecurseFrom = count($before) + min(count($nonBreakableBefore), count($mergedBefore)); - $this->matchExtends($result, $out, $startRecurseFrom, false); + $startRecurseFrom = \count($before) + min(\count($nonBreakableBefore), \count($mergedBefore)); + + if (\count($origin) > 1) { + $this->matchExtends($result, $out, $startRecurseFrom, false); + } else { + $this->matchExtends($result, $outRecurs, $startRecurseFrom, false); + } // selector sequence merging - if (! empty($before) && count($new) > 1) { - $preSharedParts = $k > 0 ? array_slice($before, 0, $k) : []; - $postSharedParts = $k > 0 ? array_slice($before, $k) : $before; + if (! empty($before) && \count($new) > 1) { + $preSharedParts = $k > 0 ? \array_slice($before, 0, $k) : []; + $postSharedParts = $k > 0 ? \array_slice($before, $k) : $before; - list($betweenSharedParts, $nonBreakable2) = $this->extractRelationshipFromFragment($afterBefore); + list($betweenSharedParts, $nonBreakabl2) = $this->extractRelationshipFromFragment($afterBefore); $result2 = array_merge( $preSharedParts, $betweenSharedParts, $postSharedParts, - $nonBreakable2, + $nonBreakabl2, $nonBreakableBefore, $replacement, $after ); - $out[] = $result2; + $this->pushOrMergeExtentedSelector($out, $result2); } } + } + array_pop($partsPile); + } + + while (\count($outRecurs)) { + $result = array_shift($outRecurs); + $this->pushOrMergeExtentedSelector($out, $result); + } + } + + /** + * Test a part for being a pseudo selector + * + * @param string $part + * @param array $matches + * + * @return boolean + */ + protected function isPseudoSelector($part, &$matches) + { + if (strpos($part, ":") === 0 + && preg_match(",^::?([\w-]+)\((.+)\)$,", $part, $matches) + ) { + return true; + } + + return false; + } + + /** + * Push extended selector except if + * - this is a pseudo selector + * - same as previous + * - in a white list + * in this case we merge the pseudo selector content + * + * @param array $out + * @param array $extended + */ + protected function pushOrMergeExtentedSelector(&$out, $extended) + { + if (\count($out) && \count($extended) === 1 && \count(reset($extended)) === 1) { + $single = reset($extended); + $part = reset($single); + + if ($this->isPseudoSelector($part, $matchesExtended) && + \in_array($matchesExtended[1], [ 'slotted' ]) + ) { + $prev = end($out); + $prev = $this->glueFunctionSelectors($prev); + + if (\count($prev) === 1 && \count(reset($prev)) === 1) { + $single = reset($prev); + $part = reset($single); - array_pop($partsPile); + if ($this->isPseudoSelector($part, $matchesPrev) && + $matchesPrev[1] === $matchesExtended[1] + ) { + $extended = explode($matchesExtended[1] . '(', $matchesExtended[0], 2); + $extended[1] = $matchesPrev[2] . ", " . $extended[1]; + $extended = implode($matchesExtended[1] . '(', $extended); + $extended = [ [ $extended ]]; + array_pop($out); + } + } } } + $out[] = $extended; } /** * Match extends single * - * @param array $rawSingle - * @param array $outOrigin + * @param array $rawSingle + * @param array $outOrigin + * @param boolean $initial * * @return boolean */ - protected function matchExtendsSingle($rawSingle, &$outOrigin) + protected function matchExtendsSingle($rawSingle, &$outOrigin, $initial = true) { $counts = []; $single = []; // simple usual cases, no need to do the whole trick - if (in_array($rawSingle, [['>'],['+'],['~']])) { + if (\in_array($rawSingle, [['>'],['+'],['~']])) { return false; } foreach ($rawSingle as $part) { // matches Number - if (! is_string($part)) { + if (! \is_string($part)) { return false; } - if (! preg_match('/^[\[.:#%]/', $part) && count($single)) { - $single[count($single) - 1] .= $part; + if (! preg_match('/^[\[.:#%]/', $part) && \count($single)) { + $single[\count($single) - 1] .= $part; } else { $single[] = $part; } @@ -661,21 +768,51 @@ protected function matchExtendsSingle($rawSingle, &$outOrigin) $extendingDecoratedTag = false; - if (count($single) > 1) { + if (\count($single) > 1) { $matches = null; $extendingDecoratedTag = preg_match('/^[a-z0-9]+$/i', $single[0], $matches) ? $matches[0] : false; } - foreach ($single as $part) { + $outOrigin = []; + $found = false; + + foreach ($single as $k => $part) { if (isset($this->extendsMap[$part])) { foreach ($this->extendsMap[$part] as $idx) { $counts[$idx] = isset($counts[$idx]) ? $counts[$idx] + 1 : 1; } } - } - $outOrigin = []; - $found = false; + if ($initial && + $this->isPseudoSelector($part, $matches) && + ! \in_array($matches[1], [ 'not' ]) + ) { + $buffer = $matches[2]; + $parser = $this->parserFactory(__METHOD__); + + if ($parser->parseSelector($buffer, $subSelectors)) { + foreach ($subSelectors as $ksub => $subSelector) { + $subExtended = []; + $this->matchExtends($subSelector, $subExtended, 0, false); + + if ($subExtended) { + $subSelectorsExtended = $subSelectors; + $subSelectorsExtended[$ksub] = $subExtended; + + foreach ($subSelectorsExtended as $ksse => $sse) { + $subSelectorsExtended[$ksse] = $this->collapseSelectors($sse); + } + + $subSelectorsExtended = implode(', ', $subSelectorsExtended); + $singleExtended = $single; + $singleExtended[$k] = str_replace("(".$buffer.")", "($subSelectorsExtended)", $part); + $outOrigin[] = [ $singleExtended ]; + $found = true; + } + } + } + } + } foreach ($counts as $idx => $count) { list($target, $origin, /* $block */) = $this->extends[$idx]; @@ -683,7 +820,7 @@ protected function matchExtendsSingle($rawSingle, &$outOrigin) $origin = $this->glueFunctionSelectors($origin); // check count - if ($count !== count($target)) { + if ($count !== \count($target)) { continue; } @@ -693,7 +830,7 @@ protected function matchExtendsSingle($rawSingle, &$outOrigin) foreach ($origin as $j => $new) { // prevent infinite loop when target extends itself - if ($this->isSelfExtend($single, $origin)) { + if ($this->isSelfExtend($single, $origin) and !$initial) { return false; } @@ -709,8 +846,8 @@ protected function matchExtendsSingle($rawSingle, &$outOrigin) $combined = $this->combineSelectorSingle($replacement, $rem); - if (count(array_diff($combined, $origin[$j][count($origin[$j]) - 1]))) { - $origin[$j][count($origin[$j]) - 1] = $combined; + if (\count(array_diff($combined, $origin[$j][\count($origin[$j]) - 1]))) { + $origin[$j][\count($origin[$j]) - 1] = $combined; } } @@ -738,12 +875,13 @@ protected function extractRelationshipFromFragment(array $fragment) { $parents = []; $children = []; - $j = $i = count($fragment); + + $j = $i = \count($fragment); for (;;) { - $children = $j != $i ? array_slice($fragment, $j, $i - $j) : []; - $parents = array_slice($fragment, 0, $j); - $slice = end($parents); + $children = $j != $i ? \array_slice($fragment, $j, $i - $j) : []; + $parents = \array_slice($fragment, 0, $j); + $slice = end($parents); if (empty($slice) || ! $this->isImmediateRelationshipCombinator($slice[0])) { break; @@ -765,30 +903,44 @@ protected function extractRelationshipFromFragment(array $fragment) */ protected function combineSelectorSingle($base, $other) { - $tag = []; - $out = []; - $wasTag = true; + $tag = []; + $out = []; + $wasTag = false; + $pseudo = []; - foreach ([$base, $other] as $single) { + while (\count($other) && strpos(end($other), ':')===0) { + array_unshift($pseudo, array_pop($other)); + } + + foreach ([array_reverse($base), array_reverse($other)] as $single) { + $rang = count($single); foreach ($single as $part) { - if (preg_match('/^[\[.:#]/', $part)) { + if (preg_match('/^[\[:]/', $part)) { $out[] = $part; $wasTag = false; - } elseif (preg_match('/^[^_-]/', $part)) { + } elseif (preg_match('/^[\.#]/', $part)) { + array_unshift($out, $part); + $wasTag = false; + } elseif (preg_match('/^[^_-]/', $part) and $rang==1) { $tag[] = $part; $wasTag = true; } elseif ($wasTag) { - $tag[count($tag) - 1] .= $part; + $tag[\count($tag) - 1] .= $part; } else { - $out[count($out) - 1] .= $part; + array_unshift($out, $part); } + $rang--; } } - if (count($tag)) { + if (\count($tag)) { array_unshift($out, $tag[0]); } + while (\count($pseudo)) { + $out[] = array_shift($pseudo); + } + return $out; } @@ -832,16 +984,17 @@ protected function compileMedia(Block $media) if ($needsWrap) { $wrapped = new Block; - $wrapped->sourceName = $media->sourceName; - $wrapped->sourceIndex = $media->sourceIndex; - $wrapped->sourceLine = $media->sourceLine; + $wrapped->sourceName = $media->sourceName; + $wrapped->sourceIndex = $media->sourceIndex; + $wrapped->sourceLine = $media->sourceLine; $wrapped->sourceColumn = $media->sourceColumn; - $wrapped->selectors = []; - $wrapped->comments = []; - $wrapped->parent = $media; - $wrapped->children = $media->children; + $wrapped->selectors = []; + $wrapped->comments = []; + $wrapped->parent = $media; + $wrapped->children = $media->children; $media->children = [[Type::T_BLOCK, $wrapped]]; + if (isset($this->lineNumberStyle)) { $annotation = $this->makeOutputBlock(Type::T_COMMENT); $annotation->depth = 0; @@ -898,20 +1051,31 @@ protected function mediaParent(OutputBlock $scope) /** * Compile directive * - * @param \ScssPhp\ScssPhp\Block $block + * @param \ScssPhp\ScssPhp\Block|array $block + * @param \ScssPhp\ScssPhp\Formatter\OutputBlock $out */ - protected function compileDirective(Block $block) + protected function compileDirective($directive, OutputBlock $out) { - $s = '@' . $block->name; + if (\is_array($directive)) { + $s = '@' . $directive[0]; - if (! empty($block->value)) { - $s .= ' ' . $this->compileValue($block->value); - } + if (! empty($directive[1])) { + $s .= ' ' . $this->compileValue($directive[1]); + } - if ($block->name === 'keyframes' || substr($block->name, -10) === '-keyframes') { - $this->compileKeyframeBlock($block, [$s]); + $this->appendRootDirective($s . ';', $out); } else { - $this->compileNestedBlock($block, [$s]); + $s = '@' . $directive->name; + + if (! empty($directive->value)) { + $s .= ' ' . $this->compileValue($directive->value); + } + + if ($directive->name === 'keyframes' || substr($directive->name, -10) === '-keyframes') { + $this->compileKeyframeBlock($directive, [$s]); + } else { + $this->compileNestedBlock($directive, [$s]); + } } } @@ -998,8 +1162,8 @@ protected function filterScopeWithWithout($scope, $with, $without) if ($this->isWith($scope, $with, $without)) { $s = clone $scope; $s->children = []; - $s->lines = []; - $s->parent = null; + $s->lines = []; + $s->parent = null; if ($s->type !== Type::T_MEDIA && $s->type !== Type::T_DIRECTIVE) { $s->selectors = []; @@ -1008,7 +1172,7 @@ protected function filterScopeWithWithout($scope, $with, $without) $filteredScopes[] = $s; } - if (count($childStash)) { + if (\count($childStash)) { $scope = array_shift($childStash); } elseif ($scope->children) { $scope = end($scope->children); @@ -1017,7 +1181,7 @@ protected function filterScopeWithWithout($scope, $with, $without) } } - if (! count($filteredScopes)) { + if (! \count($filteredScopes)) { return $this->rootBlock; } @@ -1028,7 +1192,7 @@ protected function filterScopeWithWithout($scope, $with, $without) $p = &$newScope; - while (count($filteredScopes)) { + while (\count($filteredScopes)) { $s = array_shift($filteredScopes); $s->parent = $p; $p->children[] = $s; @@ -1050,7 +1214,7 @@ protected function filterScopeWithWithout($scope, $with, $without) */ protected function completeScope($scope, $previousScope) { - if (! $scope->type && (! $scope->selectors || ! count($scope->selectors)) && count($scope->lines)) { + if (! $scope->type && (! $scope->selectors || ! \count($scope->selectors)) && \count($scope->lines)) { $scope->selectors = $this->findScopeSelectors($previousScope, $scope->depth); } @@ -1131,7 +1295,7 @@ protected function compileWith($withCondition) /** * Filter env stack * - * @param array $envs + * @param array $envs * @param array $with * @param array $without * @@ -1144,8 +1308,9 @@ protected function filterWithWithout($envs, $with, $without) foreach ($envs as $e) { if ($e->block && ! $this->isWith($e->block, $with, $without)) { $ec = clone $e; - $ec->block = null; + $ec->block = null; $ec->selectors = []; + $filtered[] = $ec; } else { $filtered[] = $e; @@ -1182,15 +1347,18 @@ protected function isWith($block, $with, $without) } } elseif (isset($block->selectors)) { // a selector starting with number is a keyframe rule - if (count($block->selectors)) { + if (\count($block->selectors)) { $s = reset($block->selectors); - while (is_array($s)) { + + while (\is_array($s)) { $s = reset($s); } - if (is_object($s) && get_class($s) === 'ScssPhp\ScssPhp\Node\Number') { + + if (\is_object($s) && $s instanceof Node\Number) { return $this->testWithWithout('keyframes', $with, $without); } } + return $this->testWithWithout('rule', $with, $without); } @@ -1203,14 +1371,15 @@ protected function isWith($block, $with, $without) * @param string $what * @param array $with * @param array $without - * @return bool + * + * @return boolean * true if the block should be kept, false to reject */ protected function testWithWithout($what, $with, $without) { // if without, reject only if in the list (or 'all' is in the list) - if (count($without)) { + if (\count($without)) { return (isset($without[$what]) || isset($without['all'])) ? false : true; } @@ -1250,8 +1419,8 @@ protected function compileKeyframeBlock(Block $block, $selectors) /** * Compile nested properties lines * - * @param \ScssPhp\ScssPhp\Block $block - * @param OutputBlock $out + * @param \ScssPhp\ScssPhp\Block $block + * @param \ScssPhp\ScssPhp\Formatter\OutputBlock $out */ protected function compileNestedPropertiesBlock(Block $block, OutputBlock $out) { @@ -1276,6 +1445,7 @@ protected function compileNestedPropertiesBlock(Block $block, OutputBlock $out) array_unshift($child[1]->prefix[2], $prefix); break; } + $this->compileChild($child, $nested); } } @@ -1308,15 +1478,15 @@ protected function compileNestedBlock(Block $block, $selectors) if ($needWrapping) { $wrapped = new Block; - $wrapped->sourceName = $block->sourceName; - $wrapped->sourceIndex = $block->sourceIndex; - $wrapped->sourceLine = $block->sourceLine; + $wrapped->sourceName = $block->sourceName; + $wrapped->sourceIndex = $block->sourceIndex; + $wrapped->sourceLine = $block->sourceLine; $wrapped->sourceColumn = $block->sourceColumn; - $wrapped->selectors = []; - $wrapped->comments = []; - $wrapped->parent = $block; - $wrapped->children = $block->children; - $wrapped->selfParent = $block->selfParent; + $wrapped->selectors = []; + $wrapped->comments = []; + $wrapped->parent = $block; + $wrapped->children = $block->children; + $wrapped->selfParent = $block->selfParent; $block->children = [[Type::T_BLOCK, $wrapped]]; } @@ -1354,7 +1524,7 @@ protected function compileBlock(Block $block) $out = $this->makeOutputBlock(null); - if (isset($this->lineNumberStyle) && count($env->selectors) && count($block->children)) { + if (isset($this->lineNumberStyle) && \count($env->selectors) && \count($block->children)) { $annotation = $this->makeOutputBlock(Type::T_COMMENT); $annotation->depth = 0; @@ -1380,7 +1550,7 @@ protected function compileBlock(Block $block) $this->scope->children[] = $out; - if (count($block->children)) { + if (\count($block->children)) { $out->selectors = $this->multiplySelectors($env, $block->selfParent); // propagate selfParent to the children where they still can be useful @@ -1393,17 +1563,52 @@ protected function compileBlock(Block $block) $this->compileChildrenNoReturn($block->children, $out, $block->selfParent); - // and revert for the following childs of the same block + // and revert for the following children of the same block if ($selfParentSelectors) { $block->selfParent->selectors = $selfParentSelectors; } } - $this->formatter->stripSemicolon($out->lines); - $this->popEnv(); } + + /** + * Compile the value of a comment that can have interpolation + * + * @param array $value + * @param boolean $pushEnv + * + * @return array|mixed|string + */ + protected function compileCommentValue($value, $pushEnv = false) + { + $c = $value[1]; + + if (isset($value[2])) { + if ($pushEnv) { + $this->pushEnv(); + } + + $ignoreCallStackMessage = $this->ignoreCallStackMessage; + $this->ignoreCallStackMessage = true; + + try { + $c = $this->compileValue($value[2]); + } catch (\Exception $e) { + // ignore error in comment compilation which are only interpolation + } + + $this->ignoreCallStackMessage = $ignoreCallStackMessage; + + if ($pushEnv) { + $this->popEnv(); + } + } + + return $c; + } + /** * Compile root level comment * @@ -1412,7 +1617,7 @@ protected function compileBlock(Block $block) protected function compileComment($block) { $out = $this->makeOutputBlock(Type::T_COMMENT); - $out->lines[] = is_string($block[1]) ? $block[1] : $this->compileValue($block[1]); + $out->lines[] = $this->compileCommentValue($block, true); $this->scope->children[] = $out; } @@ -1433,8 +1638,8 @@ protected function evalSelectors($selectors) // after evaluating interpolates, we might need a second pass if ($this->shouldEvaluate) { $selectors = $this->revertSelfSelector($selectors); - $buffer = $this->collapseSelectors($selectors); - $parser = $this->parserFactory(__METHOD__); + $buffer = $this->collapseSelectors($selectors); + $parser = $this->parserFactory(__METHOD__); if ($parser->parseSelector($buffer, $newSelectors)) { $selectors = array_map([$this, 'evalSelector'], $newSelectors); @@ -1466,14 +1671,14 @@ protected function evalSelector($selector) protected function evalSelectorPart($part) { foreach ($part as &$p) { - if (is_array($p) && ($p[0] === Type::T_INTERPOLATE || $p[0] === Type::T_STRING)) { + if (\is_array($p) && ($p[0] === Type::T_INTERPOLATE || $p[0] === Type::T_STRING)) { $p = $this->compileValue($p); // force re-evaluation if (strpos($p, '&') !== false || strpos($p, ',') !== false) { $this->shouldEvaluate = true; } - } elseif (is_string($p) && strlen($p) >= 2 && + } elseif (\is_string($p) && \strlen($p) >= 2 && ($first = $p[0]) && ($first === '"' || $first === "'") && substr($p, -1) === $first ) { @@ -1513,14 +1718,15 @@ function ($value, $key) use (&$compound) { ); if ($selectorFormat && $this->isImmediateRelationshipCombinator($compound)) { - if (count($output)) { - $output[count($output) - 1] .= ' ' . $compound; + if (\count($output)) { + $output[\count($output) - 1] .= ' ' . $compound; } else { $output[] = $compound; } + $glueNext = true; } elseif ($glueNext) { - $output[count($output) - 1] .= ' ' . $compound; + $output[\count($output) - 1] .= ' ' . $compound; $glueNext = false; } else { $output[] = $compound; @@ -1531,6 +1737,7 @@ function ($value, $key) use (&$compound) { foreach ($output as &$o) { $o = [Type::T_STRING, '', [$o]]; } + $output = [Type::T_LIST, ' ', $output]; } else { $output = implode(' ', $output); @@ -1558,7 +1765,7 @@ function ($value, $key) use (&$compound) { protected function revertSelfSelector($selectors) { foreach ($selectors as &$part) { - if (is_array($part)) { + if (\is_array($part)) { if ($part === [Type::T_SELF]) { $part = '&'; } else { @@ -1583,17 +1790,17 @@ protected function flattenSelectorSingle($single) foreach ($single as $part) { if (empty($joined) || - ! is_string($part) || + ! \is_string($part) || preg_match('/[\[.:#%]/', $part) ) { $joined[] = $part; continue; } - if (is_array(end($joined))) { + if (\is_array(end($joined))) { $joined[] = $part; } else { - $joined[count($joined) - 1] .= $part; + $joined[\count($joined) - 1] .= $part; } } @@ -1609,7 +1816,7 @@ protected function flattenSelectorSingle($single) */ protected function compileSelector($selector) { - if (! is_array($selector)) { + if (! \is_array($selector)) { return $selector; // media and the like } @@ -1632,7 +1839,7 @@ protected function compileSelector($selector) protected function compileSelectorPart($piece) { foreach ($piece as &$p) { - if (! is_array($p)) { + if (! \is_array($p)) { continue; } @@ -1659,13 +1866,13 @@ protected function compileSelectorPart($piece) */ protected function hasSelectorPlaceholder($selector) { - if (! is_array($selector)) { + if (! \is_array($selector)) { return false; } foreach ($selector as $parts) { foreach ($parts as $part) { - if (strlen($part) && '%' === $part[0]) { + if (\strlen($part) && '%' === $part[0]) { return true; } } @@ -1684,10 +1891,11 @@ protected function pushCallStack($name = '') ]; // infinite calling loop - if (count($this->callStack) > 25000) { + if (\count($this->callStack) > 25000) { // not displayed but you can var_dump it to deep debug $msg = $this->callStackMessage(true, 100); $msg = "Infinite calling loop"; + $this->throwError($msg); } } @@ -1714,6 +1922,8 @@ protected function compileChildren($stms, OutputBlock $out, $traceName = '') $ret = $this->compileChild($stm, $out); if (isset($ret)) { + $this->popCallStack(); + return $ret; } } @@ -1738,11 +1948,11 @@ protected function compileChildrenNoReturn($stms, OutputBlock $out, $selfParent $this->pushCallStack($traceName); foreach ($stms as $stm) { - if ($selfParent && isset($stm[1]) && is_object($stm[1]) && $stm[1] instanceof Block) { + if ($selfParent && isset($stm[1]) && \is_object($stm[1]) && $stm[1] instanceof Block) { $stm[1]->selfParent = $selfParent; $ret = $this->compileChild($stm, $out); $stm[1]->selfParent = null; - } elseif ($selfParent && in_array($stm[0], [TYPE::T_INCLUDE, TYPE::T_EXTEND])) { + } elseif ($selfParent && \in_array($stm[0], [TYPE::T_INCLUDE, TYPE::T_EXTEND])) { $stm['selfParent'] = $selfParent; $ret = $this->compileChild($stm, $out); unset($stm['selfParent']); @@ -1752,6 +1962,7 @@ protected function compileChildrenNoReturn($stms, OutputBlock $out, $selfParent if (isset($ret)) { $this->throwError('@return may only be used within a function'); + $this->popCallStack(); return; } @@ -1771,11 +1982,14 @@ protected function compileChildrenNoReturn($stms, OutputBlock $out, $selfParent protected function evaluateMediaQuery($queryList) { static $parser = null; + $outQueryList = []; + foreach ($queryList as $kql => $query) { $shouldReparse = false; + foreach ($query as $kq => $q) { - for ($i = 1; $i < count($q); $i++) { + for ($i = 1; $i < \count($q); $i++) { $value = $this->compileValue($q[$i]); // the parser had no mean to know if media type or expression if it was an interpolation @@ -1792,24 +2006,31 @@ protected function evaluateMediaQuery($queryList) $queryList[$kql][$kq][$i] = [Type::T_KEYWORD, $value]; } } + if ($shouldReparse) { - if (is_null($parser)) { + if (\is_null($parser)) { $parser = $this->parserFactory(__METHOD__); } + $queryString = $this->compileMediaQuery([$queryList[$kql]]); $queryString = reset($queryString); + if (strpos($queryString, '@media ') === 0) { $queryString = substr($queryString, 7); $queries = []; + if ($parser->parseMediaQueryList($queryString, $queries)) { $queries = $this->evaluateMediaQuery($queries[2]); - while (count($queries)) { + + while (\count($queries)) { $outQueryList[] = array_shift($queries); } + continue; } } } + $outQueryList[] = $queryList[$kql]; } @@ -1825,9 +2046,9 @@ protected function evaluateMediaQuery($queryList) */ protected function compileMediaQuery($queryList) { - $start = '@media '; + $start = '@media '; $default = trim($start); - $out = []; + $out = []; $current = ""; foreach ($queryList as $query) { @@ -1846,16 +2067,17 @@ protected function compileMediaQuery($queryList) foreach ($query as $q) { switch ($q[0]) { case Type::T_MEDIA_TYPE: - $newType = array_map([$this, 'compileValue'], array_slice($q, 1)); + $newType = array_map([$this, 'compileValue'], \array_slice($q, 1)); + // combining not and anything else than media type is too risky and should be avoided if (! $mediaTypeOnly) { - if (in_array(Type::T_NOT, $newType) || ($type && in_array(Type::T_NOT, $type) )) { + if (\in_array(Type::T_NOT, $newType) || ($type && \in_array(Type::T_NOT, $type) )) { if ($type) { array_unshift($parts, implode(' ', array_filter($type))); } if (! empty($parts)) { - if (strlen($current)) { + if (\strlen($current)) { $current .= $this->formatter->tagSeparator; } @@ -1867,8 +2089,8 @@ protected function compileMediaQuery($queryList) } $current = ""; - $type = null; - $parts = []; + $type = null; + $parts = []; } } @@ -1918,7 +2140,7 @@ protected function compileMediaQuery($queryList) } if (! empty($parts)) { - if (strlen($current)) { + if (\strlen($current)) { $current .= $this->formatter->tagSeparator; } @@ -2000,23 +2222,19 @@ protected function mergeMediaTypes($type1, $type2) return $type1; } - $m1 = ''; - $t1 = ''; - - if (count($type1) > 1) { - $m1= strtolower($type1[0]); - $t1= strtolower($type1[1]); + if (\count($type1) > 1) { + $m1 = strtolower($type1[0]); + $t1 = strtolower($type1[1]); } else { + $m1 = ''; $t1 = strtolower($type1[0]); } - $m2 = ''; - $t2 = ''; - - if (count($type2) > 1) { + if (\count($type2) > 1) { $m2 = strtolower($type2[0]); $t2 = strtolower($type2[1]); } else { + $m2 = ''; $t2 = strtolower($type2[0]); } @@ -2063,7 +2281,7 @@ protected function compileImport($rawPath, OutputBlock $out, $once = false) $path = $this->compileStringContent($rawPath); if ($path = $this->findImport($path)) { - if (! $once || ! in_array($path, $this->importedFiles)) { + if (! $once || ! \in_array($path, $this->importedFiles)) { $this->importFile($path, $out); $this->importedFiles[] = $path; } @@ -2078,13 +2296,14 @@ protected function compileImport($rawPath, OutputBlock $out, $once = false) if ($rawPath[0] === Type::T_LIST) { // handle a list of strings - if (count($rawPath[2]) === 0) { + if (\count($rawPath[2]) === 0) { return false; } foreach ($rawPath[2] as $path) { if ($path[0] !== Type::T_STRING) { $this->appendRootDirective('@import ' . $this->compileValue($rawPath) . ';', $out); + return false; } } @@ -2120,8 +2339,8 @@ protected function appendRootDirective($line, $out, $allowed = [Type::T_COMMENT] $i = 0; - while ($i < count($root->children)) { - if (! isset($root->children[$i]->type) || ! in_array($root->children[$i]->type, $allowed)) { + while ($i < \count($root->children)) { + if (! isset($root->children[$i]->type) || ! \in_array($root->children[$i]->type, $allowed)) { break; } @@ -2131,32 +2350,32 @@ protected function appendRootDirective($line, $out, $allowed = [Type::T_COMMENT] // remove incompatible children from the bottom of the list $saveChildren = []; - while ($i < count($root->children)) { + while ($i < \count($root->children)) { $saveChildren[] = array_pop($root->children); } // insert the directive as a comment $child = $this->makeOutputBlock(Type::T_COMMENT); - $child->lines[] = $line; - $child->sourceName = $this->sourceNames[$this->sourceIndex]; - $child->sourceLine = $this->sourceLine; + $child->lines[] = $line; + $child->sourceName = $this->sourceNames[$this->sourceIndex]; + $child->sourceLine = $this->sourceLine; $child->sourceColumn = $this->sourceColumn; $root->children[] = $child; // repush children - while (count($saveChildren)) { + while (\count($saveChildren)) { $root->children[] = array_pop($saveChildren); } } /** - * Append lines to the courrent output block: + * Append lines to the current output block: * directly to the block or through a child if necessary * * @param \ScssPhp\ScssPhp\Formatter\OutputBlock $out * @param string $type - * @param string $line + * @param string|mixed $line */ protected function appendOutputLine(OutputBlock $out, $type, $line) { @@ -2166,24 +2385,23 @@ protected function appendOutputLine(OutputBlock $out, $type, $line) $parent = $out->parent; if (end($parent->children) !== $out) { - $outWrite = &$parent->children[count($parent->children)-1]; - } - - if (!is_string($line)) { - $line = $this->compileValue($line); + $outWrite = &$parent->children[\count($parent->children) - 1]; } } // check if it's a flat output or not - if (count($out->children)) { - $lastChild = &$out->children[count($out->children) -1]; + if (\count($out->children)) { + $lastChild = &$out->children[\count($out->children) - 1]; - if ($lastChild->depth === $out->depth && is_null($lastChild->selectors) && ! count($lastChild->children)) { + if ($lastChild->depth === $out->depth && + \is_null($lastChild->selectors) && + ! \count($lastChild->children) + ) { $outWrite = $lastChild; } else { $nextLines = $this->makeOutputBlock($type); $nextLines->parent = $out; - $nextLines->depth = $out->depth; + $nextLines->depth = $out->depth; $out->children[] = $nextLines; $outWrite = &$nextLines; @@ -2204,16 +2422,17 @@ protected function appendOutputLine(OutputBlock $out, $type, $line) protected function compileChild($child, OutputBlock $out) { if (isset($child[Parser::SOURCE_LINE])) { - $this->sourceIndex = isset($child[Parser::SOURCE_INDEX]) ? $child[Parser::SOURCE_INDEX] : null; - $this->sourceLine = isset($child[Parser::SOURCE_LINE]) ? $child[Parser::SOURCE_LINE] : -1; + $this->sourceIndex = isset($child[Parser::SOURCE_INDEX]) ? $child[Parser::SOURCE_INDEX] : null; + $this->sourceLine = isset($child[Parser::SOURCE_LINE]) ? $child[Parser::SOURCE_LINE] : -1; $this->sourceColumn = isset($child[Parser::SOURCE_COLUMN]) ? $child[Parser::SOURCE_COLUMN] : -1; - } elseif (is_array($child) && isset($child[1]->sourceLine)) { - $this->sourceIndex = $child[1]->sourceIndex; - $this->sourceLine = $child[1]->sourceLine; + } elseif (\is_array($child) && isset($child[1]->sourceLine)) { + $this->sourceIndex = $child[1]->sourceIndex; + $this->sourceLine = $child[1]->sourceLine; $this->sourceColumn = $child[1]->sourceColumn; } elseif (! empty($out->sourceLine) && ! empty($out->sourceName)) { - $this->sourceLine = $out->sourceLine; - $this->sourceIndex = array_search($out->sourceName, $this->sourceNames); + $this->sourceLine = $out->sourceLine; + $this->sourceIndex = array_search($out->sourceName, $this->sourceNames); + $this->sourceColumn = $out->sourceColumn; if ($this->sourceIndex === false) { $this->sourceIndex = null; @@ -2234,7 +2453,7 @@ protected function compileChild($child, OutputBlock $out) break; case Type::T_DIRECTIVE: - $this->compileDirective($child[1]); + $this->compileDirective($child[1], $out); break; case Type::T_AT_ROOT: @@ -2256,13 +2475,37 @@ protected function compileChild($child, OutputBlock $out) } break; + case Type::T_CUSTOM_PROPERTY: + list(, $name, $value) = $child; + $compiledName = $this->compileValue($name); + + // if the value reduces to null from something else then + // the property should be discarded + if ($value[0] !== Type::T_NULL) { + $value = $this->reduce($value); + + if ($value[0] === Type::T_NULL || $value === static::$nullString) { + break; + } + } + + $compiledValue = $this->compileValue($value); + + $line = $this->formatter->customProperty( + $compiledName, + $compiledValue + ); + + $this->appendOutputLine($out, Type::T_ASSIGN, $line); + break; + case Type::T_ASSIGN: list(, $name, $value) = $child; if ($name[0] === Type::T_VARIABLE) { - $flags = isset($child[3]) ? $child[3] : []; - $isDefault = in_array('!default', $flags); - $isGlobal = in_array('!global', $flags); + $flags = isset($child[3]) ? $child[3] : []; + $isDefault = \in_array('!default', $flags); + $isGlobal = \in_array('!global', $flags); if ($isGlobal) { $this->set($name[1], $this->reduce($value), false, $this->rootEnv, $value); @@ -2270,7 +2513,7 @@ protected function compileChild($child, OutputBlock $out) } $shouldSet = $isDefault && - (($result = $this->get($name[1], false)) === null || + (\is_null($result = $this->get($name[1], false)) || $result === static::$null); if (! $isDefault || $shouldSet) { @@ -2281,28 +2524,77 @@ protected function compileChild($child, OutputBlock $out) $compiledName = $this->compileValue($name); - // handle shorthand syntax: size / line-height - if ($compiledName === 'font' || $compiledName === 'grid-row' || $compiledName === 'grid-column') { + // handle shorthand syntaxes : size / line-height... + if (\in_array($compiledName, ['font', 'grid-row', 'grid-column', 'border-radius'])) { if ($value[0] === Type::T_VARIABLE) { // if the font value comes from variable, the content is already reduced // (i.e., formulas were already calculated), so we need the original unreduced value $value = $this->get($value[1], true, null, true); } - $fontValue=&$value; + $shorthandValue=&$value; + + $shorthandDividerNeedsUnit = false; + $maxListElements = null; + $maxShorthandDividers = 1; + + switch ($compiledName) { + case 'border-radius': + $maxListElements = 4; + $shorthandDividerNeedsUnit = true; + break; + } - if ($value[0] === Type::T_LIST && $value[1]==',') { + if ($compiledName === 'font' and $value[0] === Type::T_LIST && $value[1]==',') { // this is the case if more than one font is given: example: "font: 400 1em/1.3 arial,helvetica" // we need to handle the first list element - $fontValue=&$value[2][0]; + $shorthandValue=&$value[2][0]; } - if ($fontValue[0] === Type::T_EXPRESSION && $fontValue[1] === '/') { - $fontValue = $this->expToString($fontValue); - } elseif ($fontValue[0] === Type::T_LIST) { - foreach ($fontValue[2] as &$item) { + if ($shorthandValue[0] === Type::T_EXPRESSION && $shorthandValue[1] === '/') { + $revert = true; + + if ($shorthandDividerNeedsUnit) { + $divider = $shorthandValue[3]; + + if (\is_array($divider)) { + $divider = $this->reduce($divider, true); + } + + if (\intval($divider->dimension) and ! \count($divider->units)) { + $revert = false; + } + } + + if ($revert) { + $shorthandValue = $this->expToString($shorthandValue); + } + } elseif ($shorthandValue[0] === Type::T_LIST) { + foreach ($shorthandValue[2] as &$item) { if ($item[0] === Type::T_EXPRESSION && $item[1] === '/') { - $item = $this->expToString($item); + if ($maxShorthandDividers > 0) { + $revert = true; + // if the list of values is too long, this has to be a shorthand, + // otherwise it could be a real division + if (\is_null($maxListElements) or \count($shorthandValue[2]) <= $maxListElements) { + if ($shorthandDividerNeedsUnit) { + $divider = $item[3]; + + if (\is_array($divider)) { + $divider = $this->reduce($divider, true); + } + + if (\intval($divider->dimension) and ! \count($divider->units)) { + $revert = false; + } + } + } + + if ($revert) { + $item = $this->expToString($item); + $maxShorthandDividers--; + } + } } } } @@ -2320,11 +2612,14 @@ protected function compileChild($child, OutputBlock $out) $compiledValue = $this->compileValue($value); - $line = $this->formatter->property( - $compiledName, - $compiledValue - ); - $this->appendOutputLine($out, Type::T_ASSIGN, $line); + // ignore empty value + if (\strlen($compiledValue)) { + $line = $this->formatter->property( + $compiledName, + $compiledValue + ); + $this->appendOutputLine($out, Type::T_ASSIGN, $line); + } break; case Type::T_COMMENT: @@ -2333,13 +2628,15 @@ protected function compileChild($child, OutputBlock $out) break; } - $this->appendOutputLine($out, Type::T_COMMENT, $child[1]); + $line = $this->compileCommentValue($child, true); + $this->appendOutputLine($out, Type::T_COMMENT, $line); break; case Type::T_MIXIN: case Type::T_FUNCTION: list(, $block) = $child; - + // the block need to be able to go up to it's parent env to resolve vars + $block->parentEnv = $this->getStoreEnv(); $this->set(static::$namespaces[$block->type] . $block->name, $block, true); break; @@ -2351,9 +2648,11 @@ protected function compileChild($child, OutputBlock $out) // only use the first one $result = current($result); $selectors = $out->selectors; - if (!$selectors && isset($child['selfParent'])) { + + if (! $selectors && isset($child['selfParent'])) { $selectors = $this->multiplySelectors($this->env, $child['selfParent']); } + $this->pushExtends($result, $selectors, $child); } } @@ -2378,12 +2677,12 @@ protected function compileChild($child, OutputBlock $out) case Type::T_EACH: list(, $each) = $child; - $list = $this->coerceList($this->reduce($each->list)); + $list = $this->coerceList($this->reduce($each->list), ',', true); $this->pushEnv(); foreach ($list[2] as $item) { - if (count($each->vars) === 1) { + if (\count($each->vars) === 1) { $this->set($each->vars[0], $item, true); } else { list(,, $values) = $this->coerceList($item); @@ -2397,7 +2696,9 @@ protected function compileChild($child, OutputBlock $out) if ($ret) { if ($ret[0] !== Type::T_CONTROL) { + $store = $this->env->store; $this->popEnv(); + $this->backPropagateEnv($store, $each->vars); return $ret; } @@ -2407,8 +2708,10 @@ protected function compileChild($child, OutputBlock $out) } } } - + $store = $this->env->store; $this->popEnv(); + $this->backPropagateEnv($store, $each->vars); + break; case Type::T_WHILE: @@ -2447,6 +2750,8 @@ protected function compileChild($child, OutputBlock $out) $d = $start < $end ? 1 : -1; + $this->pushEnv(); + for (;;) { if ((! $for->until && $start - $d == $end) || ($for->until && $start == $end) @@ -2461,6 +2766,9 @@ protected function compileChild($child, OutputBlock $out) if ($ret) { if ($ret[0] !== Type::T_CONTROL) { + $store = $this->env->store; + $this->popEnv(); + $this->backPropagateEnv($store, [$for->var]); return $ret; } @@ -2469,6 +2777,11 @@ protected function compileChild($child, OutputBlock $out) } } } + + $store = $this->env->store; + $this->popEnv(); + $this->backPropagateEnv($store, [$for->var]); + break; case Type::T_BREAK: @@ -2501,9 +2814,6 @@ protected function compileChild($child, OutputBlock $out) $this->pushEnv(); $this->env->depth--; - $storeEnv = $this->storeEnv; - $this->storeEnv = $this->env; - // Find the parent selectors in the env to be able to know what '&' refers to in the mixin // and assign this fake parent to childs $selfParent = null; @@ -2518,7 +2828,7 @@ protected function compileChild($child, OutputBlock $out) $parent->selectors = $parentSelectors; foreach ($mixin->children as $k => $child) { - if (isset($child[1]) && is_object($child[1]) && $child[1] instanceof Block) { + if (isset($child[1]) && \is_object($child[1]) && $child[1] instanceof Block) { $mixin->children[$k][1]->parent = $parent; } } @@ -2549,37 +2859,39 @@ protected function compileChild($child, OutputBlock $out) $this->env->marker = 'mixin'; - $this->compileChildrenNoReturn($mixin->children, $out, $selfParent, $this->env->marker . " " . $name); + if (! empty($mixin->parentEnv)) { + $this->env->declarationScopeParent = $mixin->parentEnv; + } else { + $this->throwError("@mixin $name() without parentEnv"); + } - $this->storeEnv = $storeEnv; + $this->compileChildrenNoReturn($mixin->children, $out, $selfParent, $this->env->marker . " " . $name); $this->popEnv(); break; case Type::T_MIXIN_CONTENT: - $env = isset($this->storeEnv) ? $this->storeEnv : $this->env; - $content = $this->get(static::$namespaces['special'] . 'content', false, $env); - $argUsing = $this->get(static::$namespaces['special'] . 'using', false, $env); + $env = isset($this->storeEnv) ? $this->storeEnv : $this->env; + $content = $this->get(static::$namespaces['special'] . 'content', false, $env); + $argUsing = $this->get(static::$namespaces['special'] . 'using', false, $env); $argContent = $child[1]; if (! $content) { - $content = new \stdClass(); - $content->scope = new \stdClass(); - $content->children = $env->parent->block->children; break; } $storeEnv = $this->storeEnv; - $varsUsing = []; + if (isset($argUsing) && isset($argContent)) { // Get the arguments provided for the content with the names provided in the "using" argument list - $this->storeEnv = $this->env; + $this->storeEnv = null; $varsUsing = $this->applyArguments($argUsing, $argContent, false); } // restore the scope from the @content $this->storeEnv = $content->scope; + // append the vars from using if any foreach ($varsUsing as $name => $val) { $this->set($name, $val, true, $this->storeEnv); @@ -2594,8 +2906,9 @@ protected function compileChild($child, OutputBlock $out) list(, $value) = $child; $fname = $this->sourceNames[$this->sourceIndex]; - $line = $this->sourceLine; + $line = $this->sourceLine; $value = $this->compileValue($this->reduce($value, true)); + fwrite($this->stderr, "File $fname on line $line DEBUG: $value\n"); break; @@ -2603,8 +2916,9 @@ protected function compileChild($child, OutputBlock $out) list(, $value) = $child; $fname = $this->sourceNames[$this->sourceIndex]; - $line = $this->sourceLine; + $line = $this->sourceLine; $value = $this->compileValue($this->reduce($value, true)); + fwrite($this->stderr, "File $fname on line $line WARN: $value\n"); break; @@ -2612,8 +2926,9 @@ protected function compileChild($child, OutputBlock $out) list(, $value) = $child; $fname = $this->sourceNames[$this->sourceIndex]; - $line = $this->sourceLine; + $line = $this->sourceLine; $value = $this->compileValue($this->reduce($value, true)); + $this->throwError("File $fname on line $line ERROR: $value\n"); break; @@ -2708,10 +3023,14 @@ protected function shouldEval($value) * @param array $value * @param boolean $inExp * - * @return array|\ScssPhp\ScssPhp\Node\Number + * @return null|string|array|\ScssPhp\ScssPhp\Node\Number */ protected function reduce($value, $inExp = false) { + if (\is_null($value)) { + return null; + } + switch ($value[0]) { case Type::T_EXPRESSION: list(, $op, $left, $right, $inParens) = $value; @@ -2733,9 +3052,8 @@ protected function reduce($value, $inExp = false) return $this->expToString($value); } - $left = $this->coerceForExpression($left); + $left = $this->coerceForExpression($left); $right = $this->coerceForExpression($right); - $ltype = $left[0]; $rtype = $right[0]; @@ -2749,12 +3067,12 @@ protected function reduce($value, $inExp = false) // 3. op[op name] $fn = "op${ucOpName}${ucLType}${ucRType}"; - if (is_callable([$this, $fn]) || + if (\is_callable([$this, $fn]) || (($fn = "op${ucLType}${ucRType}") && - is_callable([$this, $fn]) && + \is_callable([$this, $fn]) && $passOp = true) || (($fn = "op${ucOpName}") && - is_callable([$this, $fn]) && + \is_callable([$this, $fn]) && $genOp = true) ) { $coerceUnit = false; @@ -2789,10 +3107,18 @@ protected function reduce($value, $inExp = false) $targetUnit = $left->unitless() ? $right[2] : $left[2]; } - if (! $left->unitless() && ! $right->unitless()) { + $baseUnitLeft = $left->isNormalizable(); + $baseUnitRight = $right->isNormalizable(); + + if ($baseUnitLeft && $baseUnitRight && $baseUnitLeft === $baseUnitRight) { $left = $left->normalize(); $right = $right->normalize(); } + else { + if ($coerceUnit) { + $left = new Node\Number($left[1], []); + } + } } $shouldEval = $inParens || $inExp; @@ -2867,7 +3193,7 @@ protected function reduce($value, $inExp = false) case Type::T_STRING: foreach ($value[2] as &$item) { - if (is_array($item) || $item instanceof \ArrayAccess) { + if (\is_array($item) || $item instanceof \ArrayAccess) { $item = $this->reduce($item); } } @@ -2876,6 +3202,7 @@ protected function reduce($value, $inExp = false) case Type::T_INTERPOLATE: $value[1] = $this->reduce($value[1]); + if ($inExp) { return $value[1]; } @@ -2886,8 +3213,9 @@ protected function reduce($value, $inExp = false) return $this->fncall($value[1], $value[2]); case Type::T_SELF: - $selfSelector = $this->multiplySelectors($this->env); + $selfSelector = $this->multiplySelectors($this->env,!empty($this->env->block->selfParent) ? $this->env->block->selfParent : null); $selfSelector = $this->collapseSelectors($selfSelector, true); + return $selfSelector; default: @@ -2962,6 +3290,10 @@ public function normalizeValue($value) $value[2][$key] = $this->normalizeValue($item); } + if (! empty($value['enclosing'])) { + unset($value['enclosing']); + } + return $value; case Type::T_STRING: @@ -3028,7 +3360,7 @@ protected function opSubNumberNumber($left, $right) protected function opDivNumberNumber($left, $right) { if ($right[1] == 0) { - return [Type::T_STRING, '', [$left[1] . $left[2] . '/' . $right[1] . $right[2]]]; + return ($left[1] == 0) ? static::$NaN : static::$Infinity; } return new Node\Number($left[1] / $right[1], $left[2]); @@ -3044,6 +3376,10 @@ protected function opDivNumberNumber($left, $right) */ protected function opModNumberNumber($left, $right) { + if ($right[1] == 0) { + return static::$NaN; + } + return new Node\Number($left[1] % $right[1], $left[2]); } @@ -3378,7 +3714,7 @@ public function toBool($thing) * * @param array $value * - * @return string + * @return string|array */ public function compileValue($value) { @@ -3395,14 +3731,38 @@ public function compileValue($value) // [4] - optional alpha component list(, $r, $g, $b) = $value; - $r = round($r); - $g = round($g); - $b = round($b); + $r = $this->compileRGBAValue($r); + $g = $this->compileRGBAValue($g); + $b = $this->compileRGBAValue($b); + + if (\count($value) === 5) { + $alpha = $this->compileRGBAValue($value[4], true); + + if (! is_numeric($alpha) || $alpha < 1) { + $colorName = Colors::RGBaToColorName($r, $g, $b, $alpha); + + if (! \is_null($colorName)) { + return $colorName; + } + + if (is_numeric($alpha)) { + $a = new Node\Number($alpha, ''); + } else { + $a = $alpha; + } + + return 'rgba(' . $r . ', ' . $g . ', ' . $b . ', ' . $a . ')'; + } + } + + if (! is_numeric($r) || ! is_numeric($g) || ! is_numeric($b)) { + return 'rgb(' . $r . ', ' . $g . ', ' . $b . ')'; + } - if (count($value) === 5 && $value[4] !== 1) { // rgba - $a = new Node\Number($value[4], ''); + $colorName = Colors::RGBaToColorName($r, $g, $b); - return 'rgba(' . $r . ', ' . $g . ', ' . $b . ', ' . $a . ')'; + if (! \is_null($colorName)) { + return $colorName; } $h = sprintf('#%02x%02x%02x', $r, $g, $b); @@ -3433,9 +3793,29 @@ public function compileValue($value) } list(, $delim, $items) = $value; + $pre = $post = ""; + + if (! empty($value['enclosing'])) { + switch ($value['enclosing']) { + case 'parent': + //$pre = "("; + //$post = ")"; + break; + case 'forced_parent': + $pre = "("; + $post = ")"; + break; + case 'bracket': + case 'forced_bracket': + $pre = "["; + $post = "]"; + break; + } + } + $prefix_value = ''; if ($delim !== ' ') { - $delim .= ' '; + $prefix_value = ' '; } $filtered = []; @@ -3445,17 +3825,21 @@ public function compileValue($value) continue; } - $filtered[] = $this->compileValue($item); + $compiled = $this->compileValue($item); + if ($prefix_value && \strlen($compiled)) { + $compiled = $prefix_value . $compiled; + } + $filtered[] = $compiled; } - return implode("$delim", $filtered); + return $pre . substr(implode("$delim", $filtered), \strlen($prefix_value)) . $post; case Type::T_MAP: - $keys = $value[1]; - $values = $value[2]; + $keys = $value[1]; + $values = $value[2]; $filtered = []; - for ($i = 0, $s = count($keys); $i < $s; $i++) { + for ($i = 0, $s = \count($keys); $i < $s; $i++) { $filtered[$this->compileValue($keys[$i])] = $this->compileValue($values[$i]); } @@ -3471,17 +3855,21 @@ public function compileValue($value) list(,, $whiteLeft, $whiteRight) = $interpolate; $delim = $left[1]; - if ($delim && $delim !== ' ' && !$whiteLeft) { + + if ($delim && $delim !== ' ' && ! $whiteLeft) { $delim .= ' '; } - $left = count($left[2]) > 0 ? + + $left = \count($left[2]) > 0 ? $this->compileValue($left) . $delim . $whiteLeft: ''; $delim = $right[1]; + if ($delim && $delim !== ' ') { $delim .= ' '; } - $right = count($right[2]) > 0 ? + + $right = \count($right[2]) > 0 ? $whiteRight . $delim . $this->compileValue($right) : ''; return $left . $this->compileValue($interpolate) . $right; @@ -3512,6 +3900,7 @@ public function compileValue($value) } $temp = $this->compileValue([Type::T_KEYWORD, $item]); + if ($temp[0] === Type::T_STRING) { $filtered[] = $this->compileStringContent($temp); } elseif ($temp[0] === Type::T_KEYWORD) { @@ -3537,6 +3926,9 @@ public function compileValue($value) case Type::T_NULL: return 'null'; + case Type::T_COMMENT: + return $this->compileCommentValue($value); + default: $this->throwError("unknown value type: ".json_encode($value)); } @@ -3566,7 +3958,7 @@ protected function compileStringContent($string) $parts = []; foreach ($string[2] as $part) { - if (is_array($part) || $part instanceof \ArrayAccess) { + if (\is_array($part) || $part instanceof \ArrayAccess) { $parts[] = $this->compileValue($part); } else { $parts[] = $part; @@ -3589,8 +3981,8 @@ protected function extractInterpolation($list) foreach ($items as $i => $item) { if ($item[0] === Type::T_INTERPOLATE) { - $before = [Type::T_LIST, $list[1], array_slice($items, 0, $i)]; - $after = [Type::T_LIST, $list[1], array_slice($items, $i + 1)]; + $before = [Type::T_LIST, $list[1], \array_slice($items, 0, $i)]; + $after = [Type::T_LIST, $list[1], \array_slice($items, $i + 1)]; return [Type::T_INTERPOLATED, $item, $before, $after]; } @@ -3615,7 +4007,7 @@ protected function multiplySelectors(Environment $env, $selfParent = null) $selfParentSelectors = null; - if (! is_null($selfParent) && $selfParent->selectors) { + if (! \is_null($selfParent) && $selfParent->selectors) { $selfParentSelectors = $this->evalSelectors($selfParent->selectors); } @@ -3627,9 +4019,9 @@ protected function multiplySelectors(Environment $env, $selfParent = null) $selectors = $env->selectors; do { - $stillHasSelf = false; + $stillHasSelf = false; $prevSelectors = $selectors; - $selectors = []; + $selectors = []; foreach ($prevSelectors as $selector) { foreach ($parentSelectors as $parent) { @@ -3652,6 +4044,11 @@ protected function multiplySelectors(Environment $env, $selfParent = null) $selectors = array_values($selectors); + // case we are just starting a at-root : nothing to multiply but parentSelectors + if (!$selectors and $selfParentSelectors) { + $selectors = $selfParentSelectors; + } + return $selectors; } @@ -3660,7 +4057,7 @@ protected function multiplySelectors(Environment $env, $selfParent = null) * * @param array $parent * @param array $child - * @param boolean &$stillHasSelf + * @param boolean $stillHasSelf * @param array $selfParentSelectors * @return array @@ -3682,7 +4079,7 @@ protected function joinSelectors($parent, $child, &$stillHasSelf, $selfParentSel if ($p === static::$selfSelector && ! $setSelf) { $setSelf = true; - if (is_null($selfParentSelectors)) { + if (\is_null($selfParentSelectors)) { $selfParentSelectors = $parent; } @@ -3693,11 +4090,13 @@ protected function joinSelectors($parent, $child, &$stillHasSelf, $selfParentSel } foreach ($parentPart as $pp) { - if (is_array($pp)) { + if (\is_array($pp)) { $flatten = []; + array_walk_recursive($pp, function ($a) use (&$flatten) { $flatten[] = $a; }); + $pp = implode($flatten); } @@ -3741,12 +4140,14 @@ protected function multiplyMedia(Environment $env = null, $childQueries = null) : [[[Type::T_MEDIA_VALUE, $env->block->value]]]; $store = [$this->env, $this->storeEnv]; - $this->env = $env; + + $this->env = $env; $this->storeEnv = null; - $parentQueries = $this->evaluateMediaQuery($parentQueries); + $parentQueries = $this->evaluateMediaQuery($parentQueries); + list($this->env, $this->storeEnv) = $store; - if ($childQueries === null) { + if (\is_null($childQueries)) { $childQueries = $parentQueries; } else { $originalQueries = $childQueries; @@ -3810,11 +4211,13 @@ protected function pushEnv(Block $block = null) { $env = new Environment; $env->parent = $this->env; + $env->parentStore = $this->storeEnv; $env->store = []; $env->block = $block; $env->depth = isset($this->env->depth) ? $this->env->depth + 1 : 0; $this->env = $env; + $this->storeEnv = null; return $env; } @@ -3824,9 +4227,25 @@ protected function pushEnv(Block $block = null) */ protected function popEnv() { + $this->storeEnv = $this->env->parentStore; $this->env = $this->env->parent; } + /** + * Propagate vars from a just poped Env (used in @each and @for) + * + * @param array $store + * @param null|array $excludedVars + */ + protected function backPropagateEnv($store, $excludedVars = null) + { + foreach ($store as $key => $value) { + if (empty($excludedVars) || ! \in_array($key, $excludedVars)) { + $this->set($key, $value, true); + } + } + } + /** * Get store environment * @@ -3872,25 +4291,44 @@ protected function set($name, $value, $shadow = false, Environment $env = null, protected function setExisting($name, $value, Environment $env, $valueUnreduced = null) { $storeEnv = $env; + $specialContentKey = static::$namespaces['special'] . 'content'; $hasNamespace = $name[0] === '^' || $name[0] === '@' || $name[0] === '%'; + $maxDepth = 10000; + for (;;) { - if (array_key_exists($name, $env->store)) { + if ($maxDepth-- <= 0) { break; } - if (! $hasNamespace && isset($env->marker)) { - $env = $storeEnv; + if (\array_key_exists($name, $env->store)) { break; } - if (! isset($env->parent)) { + if (! $hasNamespace && isset($env->marker)) { + if (! empty($env->store[$specialContentKey])) { + $env = $env->store[$specialContentKey]->scope; + continue; + } + + if (! empty($env->declarationScopeParent)) { + $env = $env->declarationScopeParent; + continue; + } else { + $env = $storeEnv; + break; + } + } + + if (isset($env->parentStore)) { + $env = $env->parentStore; + } elseif (isset($env->parent)) { + $env = $env->parent; + } else { $env = $storeEnv; break; } - - $env = $env->parent; } $env->store[$name] = $value; @@ -3938,7 +4376,6 @@ public function get($name, $shouldThrow = true, Environment $env = null, $unredu $env = $this->getStoreEnv(); } - $nextIsRoot = false; $hasNamespace = $normalizedName[0] === '^' || $normalizedName[0] === '@' || $normalizedName[0] === '%'; $maxDepth = 10000; @@ -3948,7 +4385,7 @@ public function get($name, $shouldThrow = true, Environment $env = null, $unredu break; } - if (array_key_exists($normalizedName, $env->store)) { + if (\array_key_exists($normalizedName, $env->store)) { if ($unreduced && isset($env->storeUnreduced[$normalizedName])) { return $env->storeUnreduced[$normalizedName]; } @@ -3957,24 +4394,30 @@ public function get($name, $shouldThrow = true, Environment $env = null, $unredu } if (! $hasNamespace && isset($env->marker)) { - if (! $nextIsRoot && ! empty($env->store[$specialContentKey])) { + if (! empty($env->store[$specialContentKey])) { $env = $env->store[$specialContentKey]->scope; continue; } - $env = $this->rootEnv; + if (! empty($env->declarationScopeParent)) { + $env = $env->declarationScopeParent; + } else { + $env = $this->rootEnv; + } continue; } - if (! isset($env->parent)) { + if (isset($env->parentStore)) { + $env = $env->parentStore; + } elseif (isset($env->parent)) { + $env = $env->parent; + } else { break; } - - $env = $env->parent; } if ($shouldThrow) { - $this->throwError("Undefined variable \$$name" . ($maxDepth<=0 ? " (infinite recursion)" : "")); + $this->throwError("Undefined variable \$$name" . ($maxDepth <= 0 ? " (infinite recursion)" : "")); } // found nothing @@ -3991,7 +4434,7 @@ public function get($name, $shouldThrow = true, Environment $env = null, $unredu */ protected function has($name, Environment $env = null) { - return $this->get($name, false, $env) !== null; + return ! \is_null($this->get($name, false, $env)); } /** @@ -4065,7 +4508,7 @@ public function getVariables() */ public function addParsedFile($path) { - if (isset($path) && file_exists($path)) { + if (isset($path) && is_file($path)) { $this->parsedFiles[realpath($path)] = filemtime($path); } } @@ -4091,7 +4534,7 @@ public function getParsedFiles() */ public function addImportPath($path) { - if (! in_array($path, $this->importPaths)) { + if (! \in_array($path, $this->importPaths)) { $this->importPaths[] = $path; } } @@ -4214,6 +4657,7 @@ public function addFeature($name) */ protected function importFile($path, OutputBlock $out) { + $this->pushCallStack('import '.$path); // see if tree is cached $realPath = realpath($path); @@ -4230,9 +4674,11 @@ protected function importFile($path, OutputBlock $out) } $pi = pathinfo($path); + array_unshift($this->importPaths, $pi['dirname']); $this->compileChildrenNoReturn($tree->children, $out); array_shift($this->importPaths); + $this->popCallStack(); } /** @@ -4248,16 +4694,29 @@ public function findImport($url) { $urls = []; + $hasExtension = preg_match('/[.]s?css$/', $url); + // for "normal" scss imports (ignore vanilla css and external requests) - if (! preg_match('/\.css$|^https?:\/\//', $url)) { + if (! preg_match('~\.css$|^https?://|^//~', $url)) { + $isPartial = (strpos(basename($url), '_') === 0); + // try both normal and the _partial filename - $urls = [$url, preg_replace('/[^\/]+$/', '_\0', $url)]; - } + $urls = [$url . ($hasExtension ? '' : '.scss')]; - $hasExtension = preg_match('/[.]s?css$/', $url); + if (! $isPartial) { + $urls[] = preg_replace('~[^/]+$~', '_\0', $url) . ($hasExtension ? '' : '.scss'); + } + + if (! $hasExtension) { + $urls[] = "$url/index.scss"; + $urls[] = "$url/_index.scss"; + // allow to find a plain css file, *if* no scss or partial scss is found + $urls[] .= $url . ".css"; + } + } foreach ($this->importPaths as $dir) { - if (is_string($dir)) { + if (\is_string($dir)) { // check urls for normal import paths foreach ($urls as $full) { $separator = ( @@ -4267,22 +4726,26 @@ public function findImport($url) ) ? '/' : ''; $full = $dir . $separator . $full; - if ($this->fileExists($file = $full . '.scss') || - ($hasExtension && $this->fileExists($file = $full)) - ) { + if (is_file($file = $full)) { return $file; } } - } elseif (is_callable($dir)) { + } elseif (\is_callable($dir)) { // check custom callback for import path - $file = call_user_func($dir, $url); + $file = \call_user_func($dir, $url); - if ($file !== null) { + if (! \is_null($file)) { return $file; } } } + if ($urls) { + if (! $hasExtension or preg_match('/[.]scss$/', $url)) { + $this->throwError("`$url` file not found for @import"); + } + } + return null; } @@ -4329,23 +4792,25 @@ public function throwError($msg) return; } - $line = $this->sourceLine; - $column = $this->sourceColumn; + if (\func_num_args() > 1) { + $msg = \call_user_func_array('sprintf', \func_get_args()); + } - $loc = isset($this->sourceNames[$this->sourceIndex]) - ? $this->sourceNames[$this->sourceIndex] . " on line $line, at column $column" - : "line: $line, column: $column"; + if (! $this->ignoreCallStackMessage) { + $line = $this->sourceLine; + $column = $this->sourceColumn; - if (func_num_args() > 1) { - $msg = call_user_func_array('sprintf', func_get_args()); - } + $loc = isset($this->sourceNames[$this->sourceIndex]) + ? $this->sourceNames[$this->sourceIndex] . " on line $line, at column $column" + : "line: $line, column: $column"; - $msg = "$msg: $loc"; + $msg = "$msg: $loc"; - $callStackMsg = $this->callStackMessage(); + $callStackMsg = $this->callStackMessage(); - if ($callStackMsg) { - $msg .= "\nCall Stack:\n" . $callStackMsg; + if ($callStackMsg) { + $msg .= "\nCall Stack:\n" . $callStackMsg; + } } throw new CompilerException($msg); @@ -4372,9 +4837,10 @@ protected function callStackMessage($all = false, $limit = null) ? $this->sourceNames[$call[Parser::SOURCE_INDEX]] : '(unknown file)'); $msg .= " on line " . $call[Parser::SOURCE_LINE]; + $callStackMsg[] = $msg; - if (! is_null($limit) && $ncall>$limit) { + if (! \is_null($limit) && $ncall > $limit) { break; } } @@ -4394,6 +4860,10 @@ protected function callStackMessage($all = false, $limit = null) protected function handleImportLoop($name) { for ($env = $this->env; $env; $env = $env->parent) { + if (! $env->block) { + continue; + } + $file = $this->sourceNames[$env->block->sourceIndex]; if (realpath($file) === $name) { @@ -4403,18 +4873,6 @@ protected function handleImportLoop($name) } } - /** - * Does file exist? - * - * @param string $name - * - * @return boolean - */ - protected function fileExists($name) - { - return file_exists($name) && is_file($name); - } - /** * Call SCSS @function * @@ -4434,9 +4892,6 @@ protected function callScssFunction($name, $argValues, &$returnValue) $this->pushEnv(); - $storeEnv = $this->storeEnv; - $this->storeEnv = $this->env; - // set the args if (isset($func->args)) { $this->applyArguments($func->args, $argValues); @@ -4449,9 +4904,13 @@ protected function callScssFunction($name, $argValues, &$returnValue) $this->env->marker = 'function'; - $ret = $this->compileChildren($func->children, $tmp, $this->env->marker . " " . $name); + if (! empty($func->parentEnv)) { + $this->env->declarationScopeParent = $func->parentEnv; + } else { + $this->throwError("@function $name() without parentEnv"); + } - $this->storeEnv = $storeEnv; + $ret = $this->compileChildren($func->children, $tmp, $this->env->marker . " " . $name); $this->popEnv(); @@ -4473,30 +4932,33 @@ protected function callNativeFunction($name, $args, &$returnValue) { // try a lib function $name = $this->normalizeName($name); + $libName = null; if (isset($this->userFunctions[$name])) { // see if we can find a user function list($f, $prototype) = $this->userFunctions[$name]; - } elseif (($f = $this->getBuiltinFunction($name)) && is_callable($f)) { + } elseif (($f = $this->getBuiltinFunction($name)) && \is_callable($f)) { $libName = $f[1]; $prototype = isset(static::$$libName) ? static::$$libName : null; } else { return false; } - @list($sorted, $kwargs) = $this->sortNativeFunctionArgs($prototype, $args); + @list($sorted, $kwargs) = $this->sortNativeFunctionArgs($libName, $prototype, $args); if ($name !== 'if' && $name !== 'call') { $inExp = true; + if ($name === 'join') { $inExp = false; } + foreach ($sorted as &$val) { $val = $this->reduce($val, $inExp); } } - $returnValue = call_user_func($f, $sorted, $kwargs); + $returnValue = \call_user_func($f, $sorted, $kwargs); if (! isset($returnValue)) { return false; @@ -4530,12 +4992,13 @@ function ($m) { /** * Sorts keyword arguments * - * @param array $prototype - * @param array $args + * @param string $functionName + * @param array $prototypes + * @param array $args * * @return array */ - protected function sortNativeFunctionArgs($prototypes, $args) + protected function sortNativeFunctionArgs($functionName, $prototypes, $args) { static $parser = null; @@ -4559,9 +5022,26 @@ protected function sortNativeFunctionArgs($prototypes, $args) return [$posArgs, $keyArgs]; } + // specific cases ? + if (\in_array($functionName, ['libRgb', 'libRgba', 'libHsl', 'libHsla'])) { + // notation 100 127 255 / 0 is in fact a simple list of 4 values + foreach ($args as $k => $arg) { + if ($arg[1][0] === Type::T_LIST && \count($arg[1][2]) === 3) { + $last = end($arg[1][2]); + + if ($last[0] === Type::T_EXPRESSION && $last[1] === '/') { + array_pop($arg[1][2]); + $arg[1][2][] = $last[2]; + $arg[1][2][] = $last[3]; + $args[$k] = $arg; + } + } + } + } + $finalArgs = []; - if (! is_array(reset($prototypes))) { + if (! \is_array(reset($prototypes))) { $prototypes = [$prototypes]; } @@ -4579,14 +5059,14 @@ protected function sortNativeFunctionArgs($prototypes, $args) $p = explode(':', $p, 2); $name = array_shift($p); - if (count($p)) { + if (\count($p)) { $p = trim(reset($p)); if ($p === 'null') { // differentiate this null from the static::$null $default = [Type::T_KEYWORD, 'null']; } else { - if (is_null($parser)) { + if (\is_null($parser)) { $parser = $this->parserFactory(__METHOD__); } @@ -4604,6 +5084,9 @@ protected function sortNativeFunctionArgs($prototypes, $args) $argDef[] = [$name, $default, $isVariable]; } + $ignoreCallStackMessage = $this->ignoreCallStackMessage; + $this->ignoreCallStackMessage = true; + try { $vars = $this->applyArguments($argDef, $args, false, false); @@ -4641,6 +5124,7 @@ protected function sortNativeFunctionArgs($prototypes, $args) } catch (CompilerException $e) { $exceptionMessage = $e->getMessage(); } + $this->ignoreCallStackMessage = $ignoreCallStackMessage; } if ($exceptionMessage && ! $prototypeHasMatch) { @@ -4653,17 +5137,24 @@ protected function sortNativeFunctionArgs($prototypes, $args) /** * Apply argument values per definition * - * @param array $argDef - * @param array $argValues - * @param bool $storeInEnv - * @param bool $reduce + * @param array $argDef + * @param array $argValues + * @param boolean $storeInEnv + * @param boolean $reduce * only used if $storeInEnv = false + * + * @return array + * * @throws \Exception */ protected function applyArguments($argDef, $argValues, $storeInEnv = true, $reduce = true) { $output = []; + if (\is_array($argValues) && \count($argValues) && end($argValues) === static::$null) { + array_pop($argValues); + } + if ($storeInEnv) { $storeEnv = $this->getStoreEnv(); @@ -4692,18 +5183,28 @@ protected function applyArguments($argDef, $argValues, $storeInEnv = true, $redu if (! empty($arg[0])) { $hasKeywordArgument = true; - if (! isset($args[$arg[0][1]]) || $args[$arg[0][1]][3]) { + $name = $arg[0][1]; + if (! isset($args[$name])) { + foreach (array_keys($args) as $an) { + if (str_replace("_", "-", $an) === str_replace("_", "-", $name)) { + $name = $an; + break; + } + } + } + + if (! isset($args[$name]) || $args[$name][3]) { if ($hasVariable) { - $deferredKeywordArgs[$arg[0][1]] = $arg[1]; + $deferredKeywordArgs[$name] = $arg[1]; } else { $this->throwError("Mixin or function doesn't have an argument named $%s.", $arg[0][1]); break; } - } elseif ($args[$arg[0][1]][0] < count($remaining)) { + } elseif ($args[$name][0] < \count($remaining)) { $this->throwError("The argument $%s was passed both by position and by name.", $arg[0][1]); break; } else { - $keywordArgs[$arg[0][1]] = $arg[1]; + $keywordArgs[$name] = $arg[1]; } } elseif ($arg[2] === true) { $val = $this->reduce($arg[1], true); @@ -4711,7 +5212,7 @@ protected function applyArguments($argDef, $argValues, $storeInEnv = true, $redu if ($val[0] === Type::T_LIST) { foreach ($val[2] as $name => $item) { if (! is_numeric($name)) { - if (!isset($args[$name])) { + if (! isset($args[$name])) { foreach (array_keys($args) as $an) { if (str_replace("_", "-", $an) === str_replace("_", "-", $name)) { $name = $an; @@ -4726,9 +5227,10 @@ protected function applyArguments($argDef, $argValues, $storeInEnv = true, $redu $keywordArgs[$name] = $item; } } else { - if (is_null($splatSeparator)) { + if (\is_null($splatSeparator)) { $splatSeparator = $val[1]; } + $remaining[] = $item; } } @@ -4738,7 +5240,7 @@ protected function applyArguments($argDef, $argValues, $storeInEnv = true, $redu $item = $val[2][$i]; if (! is_numeric($name)) { - if (!isset($args[$name])) { + if (! isset($args[$name])) { foreach (array_keys($args) as $an) { if (str_replace("_", "-", $an) === str_replace("_", "-", $name)) { $name = $an; @@ -4746,15 +5248,17 @@ protected function applyArguments($argDef, $argValues, $storeInEnv = true, $redu } } } + if ($hasVariable) { $deferredKeywordArgs[$name] = $item; } else { $keywordArgs[$name] = $item; } } else { - if (is_null($splatSeparator)) { + if (\is_null($splatSeparator)) { $splatSeparator = $val[1]; } + $remaining[] = $item; } } @@ -4773,9 +5277,9 @@ protected function applyArguments($argDef, $argValues, $storeInEnv = true, $redu list($i, $name, $default, $isVariable) = $arg; if ($isVariable) { - $val = [Type::T_LIST, is_null($splatSeparator) ? ',' : $splatSeparator , [], $isVariable]; + $val = [Type::T_LIST, \is_null($splatSeparator) ? ',' : $splatSeparator , [], $isVariable]; - for ($count = count($remaining); $i < $count; $i++) { + for ($count = \count($remaining); $i < $count; $i++) { $val[2][] = $remaining[$i]; } @@ -4830,15 +5334,15 @@ protected function applyArguments($argDef, $argValues, $storeInEnv = true, $redu */ protected function coerceValue($value) { - if (is_array($value) || $value instanceof \ArrayAccess) { + if (\is_array($value) || $value instanceof \ArrayAccess) { return $value; } - if (is_bool($value)) { + if (\is_bool($value)) { return $this->toBool($value); } - if ($value === null) { + if (\is_null($value)) { return static::$null; } @@ -4850,30 +5354,14 @@ protected function coerceValue($value) return static::$emptyString; } - if (preg_match('/^(#([0-9a-f]{6})|#([0-9a-f]{3}))$/i', $value, $m)) { - $color = [Type::T_COLOR]; - - if (isset($m[3])) { - $num = hexdec($m[3]); - - foreach ([3, 2, 1] as $i) { - $t = $num & 0xf; - $color[$i] = $t << 4 | $t; - $num >>= 4; - } - } else { - $num = hexdec($m[2]); - - foreach ([3, 2, 1] as $i) { - $color[$i] = $num & 0xff; - $num >>= 8; - } - } + $value = [Type::T_KEYWORD, $value]; + $color = $this->coerceColor($value); + if ($color) { return $color; } - return [Type::T_KEYWORD, $value]; + return $value; } /** @@ -4889,7 +5377,10 @@ protected function coerceMap($item) return $item; } - if ($item === static::$emptyList) { + if ($item[0] === static::$emptyList[0] && + $item[1] === static::$emptyList[1] && + $item[2] === static::$emptyList[2] + ) { return static::$emptyMap; } @@ -4899,14 +5390,20 @@ protected function coerceMap($item) /** * Coerce something to list * - * @param array $item - * @param string $delim + * @param array $item + * @param string $delim + * @param boolean $removeTrailingNull * * @return array */ - protected function coerceList($item, $delim = ',') + protected function coerceList($item, $delim = ',', $removeTrailingNull = false) { if (isset($item) && $item[0] === Type::T_LIST) { + // remove trailing null from the list + if ($removeTrailingNull && end($item[2]) === static::$null) { + array_pop($item[2]); + } + return $item; } @@ -4915,13 +5412,15 @@ protected function coerceList($item, $delim = ',') $values = $item[2]; $list = []; - for ($i = 0, $s = count($keys); $i < $s; $i++) { + for ($i = 0, $s = \count($keys); $i < $s; $i++) { $key = $keys[$i]; $value = $values[$i]; switch ($key[0]) { case Type::T_LIST: case Type::T_MAP: + case Type::T_STRING: + case Type::T_NULL: break; default: @@ -4965,21 +5464,107 @@ protected function coerceForExpression($value) * * @return array|null */ - protected function coerceColor($value) + protected function coerceColor($value, $inRGBFunction = false) { switch ($value[0]) { case Type::T_COLOR: + for ($i = 1; $i <= 3; $i++) { + if (! is_numeric($value[$i])) { + $cv = $this->compileRGBAValue($value[$i]); + + if (! is_numeric($cv)) { + return null; + } + + $value[$i] = $cv; + } + + if (isset($value[4])) { + if (! is_numeric($value[4])) { + $cv = $this->compileRGBAValue($value[4], true); + + if (! is_numeric($cv)) { + return null; + } + + $value[4] = $cv; + } + } + } + return $value; + case Type::T_LIST: + if ($inRGBFunction) { + if (\count($value[2]) == 3 || \count($value[2]) == 4) { + $color = $value[2]; + array_unshift($color, Type::T_COLOR); + + return $this->coerceColor($color); + } + } + + return null; + case Type::T_KEYWORD: + if (! \is_string($value[1])) { + return null; + } + $name = strtolower($value[1]); - if (isset(Colors::$cssColors[$name])) { - $rgba = explode(',', Colors::$cssColors[$name]); + // hexa color? + if (preg_match('/^#([0-9a-f]+)$/i', $name, $m)) { + $nofValues = \strlen($m[1]); + + if (\in_array($nofValues, [3, 4, 6, 8])) { + $nbChannels = 3; + $color = []; + $num = hexdec($m[1]); + + switch ($nofValues) { + case 4: + $nbChannels = 4; + // then continuing with the case 3: + case 3: + for ($i = 0; $i < $nbChannels; $i++) { + $t = $num & 0xf; + array_unshift($color, $t << 4 | $t); + $num >>= 4; + } + + break; + + case 8: + $nbChannels = 4; + // then continuing with the case 6: + case 6: + for ($i = 0; $i < $nbChannels; $i++) { + array_unshift($color, $num & 0xff); + $num >>= 8; + } + + break; + } + + if ($nbChannels === 4) { + if ($color[3] === 255) { + $color[3] = 1; // fully opaque + } else { + $color[3] = round($color[3] / 255, 3); + } + } + + array_unshift($color, Type::T_COLOR); + return $color; + } + } + + if ($rgba = Colors::colorNameToRGBa($name)) { return isset($rgba[3]) - ? [Type::T_COLOR, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2], (int) $rgba[3]] - : [Type::T_COLOR, (int) $rgba[0], (int) $rgba[1], (int) $rgba[2]]; + ? [Type::T_COLOR, $rgba[0], $rgba[1], $rgba[2], $rgba[3]] + : [Type::T_COLOR, $rgba[0], $rgba[1], $rgba[2]]; } return null; @@ -4988,6 +5573,88 @@ protected function coerceColor($value) return null; } + /** + * @param integer|\ScssPhp\ScssPhp\Node\Number $value + * @param boolean $isAlpha + * + * @return integer|mixed + */ + protected function compileRGBAValue($value, $isAlpha = false) + { + if ($isAlpha) { + return $this->compileColorPartValue($value, 0, 1, false); + } + + return $this->compileColorPartValue($value, 0, 255, true); + } + + /** + * @param mixed $value + * @param integer|float $min + * @param integer|float $max + * @param boolean $isInt + * @param boolean $clamp + * @param boolean $modulo + * + * @return integer|mixed + */ + protected function compileColorPartValue($value, $min, $max, $isInt = true, $clamp = true, $modulo = false) + { + if (! is_numeric($value)) { + if (\is_array($value)) { + $reduced = $this->reduce($value); + + if (\is_object($reduced) && $value->type === Type::T_NUMBER) { + $value = $reduced; + } + } + + if (\is_object($value) && $value->type === Type::T_NUMBER) { + $num = $value->dimension; + + if (\count($value->units)) { + $unit = array_keys($value->units); + $unit = reset($unit); + + switch ($unit) { + case '%': + $num *= $max / 100; + break; + default: + break; + } + } + + $value = $num; + } elseif (\is_array($value)) { + $value = $this->compileValue($value); + } + } + + if (is_numeric($value)) { + if ($isInt) { + $value = round($value); + } + + if ($clamp) { + $value = min($max, max($min, $value)); + } + + if ($modulo) { + $value = $value % $max; + + // still negative? + while ($value < $min) { + $value += $max; + } + } + + return $value; + } + + return $value; + } + /** * Coerce value to string * @@ -5272,10 +5939,6 @@ protected function libIndex($args) { list($list, $value) = $args; - if ($value[0] === Type::T_MAP) { - return static::$null; - } - if ($list[0] === Type::T_MAP || $list[0] === Type::T_STRING || $list[0] === Type::T_KEYWORD || @@ -5299,30 +5962,68 @@ protected function libIndex($args) return false === $key ? static::$null : $key + 1; } - protected static $libRgb = ['red', 'green', 'blue']; - protected function libRgb($args) + protected static $libRgb = [ + ['color'], + ['color', 'alpha'], + ['channels'], + ['red', 'green', 'blue'], + ['red', 'green', 'blue', 'alpha'] ]; + protected function libRgb($args, $kwargs, $funcName = 'rgb') { - list($r, $g, $b) = $args; + switch (\count($args)) { + case 1: + if (! $color = $this->coerceColor($args[0], true)) { + $color = [Type::T_STRING, '', [$funcName . '(', $args[0], ')']]; + } + break; - return [Type::T_COLOR, $r[1], $g[1], $b[1]]; - } + case 3: + $color = [Type::T_COLOR, $args[0], $args[1], $args[2]]; - protected static $libRgba = [ - ['color', 'alpha:1'], - ['red', 'green', 'blue', 'alpha:1'] ]; - protected function libRgba($args) - { - if ($color = $this->coerceColor($args[0])) { - $num = isset($args[3]) ? $args[3] : $args[1]; - $alpha = $this->assertNumber($num); - $color[4] = $alpha; + if (! $color = $this->coerceColor($color)) { + $color = [Type::T_STRING, '', [$funcName .'(', $args[0], ', ', $args[1], ', ', $args[2], ')']]; + } - return $color; + return $color; + + case 2: + if ($color = $this->coerceColor($args[0], true)) { + $alpha = $this->compileRGBAValue($args[1], true); + + if (is_numeric($alpha)) { + $color[4] = $alpha; + } else { + $color = [Type::T_STRING, '', + [$funcName . '(', $color[1], ', ', $color[2], ', ', $color[3], ', ', $alpha, ')']]; + } + } else { + $color = [Type::T_STRING, '', [$funcName . '(', $args[0], ')']]; + } + break; + + case 4: + default: + $color = [Type::T_COLOR, $args[0], $args[1], $args[2], $args[3]]; + + if (! $color = $this->coerceColor($color)) { + $color = [Type::T_STRING, '', + [$funcName . '(', $args[0], ', ', $args[1], ', ', $args[2], ', ', $args[3], ')']]; + } + break; } - list($r, $g, $b, $a) = $args; + return $color; + } - return [Type::T_COLOR, $r[1], $g[1], $b[1], $a[1]]; + protected static $libRgba = [ + ['color'], + ['color', 'alpha'], + ['channels'], + ['red', 'green', 'blue'], + ['red', 'green', 'blue', 'alpha'] ]; + protected function libRgba($args, $kwargs) + { + return $this->libRgb($args, $kwargs, 'rgba'); } // helper function for adjust_color, change_color, and scale_color @@ -5330,21 +6031,25 @@ protected function alterColor($args, $fn) { $color = $this->assertColor($args[0]); - foreach ([1, 2, 3, 7] as $i) { - if (isset($args[$i])) { - $val = $this->assertNumber($args[$i]); - $ii = $i === 7 ? 4 : $i; // alpha - $color[$ii] = call_user_func($fn, isset($color[$ii]) ? $color[$ii] : 0, $val, $i); + foreach ([1 => 1, 2 => 2, 3 => 3, 7 => 4] as $iarg => $irgba) { + if (isset($args[$iarg])) { + $val = $this->assertNumber($args[$iarg]); + + if (! isset($color[$irgba])) { + $color[$irgba] = (($irgba < 4) ? 0 : 1); + } + + $color[$irgba] = \call_user_func($fn, $color[$irgba], $val, $iarg); } } if (! empty($args[4]) || ! empty($args[5]) || ! empty($args[6])) { $hsl = $this->toHSL($color[1], $color[2], $color[3]); - foreach ([4, 5, 6] as $i) { - if (! empty($args[$i])) { - $val = $this->assertNumber($args[$i]); - $hsl[$i - 3] = call_user_func($fn, $hsl[$i - 3], $val, $i); + foreach ([4 => 1, 5 => 2, 6 => 3] as $iarg => $ihsl) { + if (! empty($args[$iarg])) { + $val = $this->assertNumber($args[$iarg]); + $hsl[$ihsl] = \call_user_func($fn, $hsl[$ihsl], $val, $iarg); } } @@ -5427,7 +6132,7 @@ protected function libIeHexStr($args) $color = $this->coerceColor($args[0]); $color[4] = isset($color[4]) ? round(255 * $color[4]) : 255; - return sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3]); + return [Type::T_STRING, '', [sprintf('#%02X%02X%02X%02X', $color[4], $color[1], $color[2], $color[3])]]; } protected static $libRed = ['color']; @@ -5514,25 +6219,56 @@ protected function libMix($args) return $this->fixColor($new); } - protected static $libHsl = ['hue', 'saturation', 'lightness']; - protected function libHsl($args) + protected static $libHsl =[ + ['channels'], + ['hue', 'saturation', 'lightness'], + ['hue', 'saturation', 'lightness', 'alpha'] ]; + protected function libHsl($args, $kwargs, $funcName = 'hsl') { - list($h, $s, $l) = $args; + if (\count($args) == 1) { + if ($args[0][0] !== Type::T_LIST || \count($args[0][2]) < 3 || \count($args[0][2]) > 4) { + return [Type::T_STRING, '', [$funcName . '(', $args[0], ')']]; + } - return $this->toRGB($h[1], $s[1], $l[1]); - } + $args = $args[0][2]; + } - protected static $libHsla = ['hue', 'saturation', 'lightness', 'alpha']; - protected function libHsla($args) - { - list($h, $s, $l, $a) = $args; + $hue = $this->compileColorPartValue($args[0], 0, 360, false, false, true); + $saturation = $this->compileColorPartValue($args[1], 0, 100, false); + $lightness = $this->compileColorPartValue($args[2], 0, 100, false); + + $alpha = null; + + if (\count($args) === 4) { + $alpha = $this->compileColorPartValue($args[3], 0, 100, false); + + if (! is_numeric($hue) || ! is_numeric($saturation) || ! is_numeric($lightness) || ! is_numeric($alpha)) { + return [Type::T_STRING, '', + [$funcName . '(', $args[0], ', ', $args[1], ', ', $args[2], ', ', $args[3], ')']]; + } + } else { + if (! is_numeric($hue) || ! is_numeric($saturation) || ! is_numeric($lightness)) { + return [Type::T_STRING, '', [$funcName . '(', $args[0], ', ', $args[1], ', ', $args[2], ')']]; + } + } - $color = $this->toRGB($h[1], $s[1], $l[1]); - $color[4] = $a[1]; + $color = $this->toRGB($hue, $saturation, $lightness); + + if (! \is_null($alpha)) { + $color[4] = $alpha; + } return $color; } + protected static $libHsla = [ + ['channels'], + ['hue', 'saturation', 'lightness', 'alpha:1'] ]; + protected function libHsla($args, $kwargs) + { + return $this->libHsl($args, $kwargs, 'hsla'); + } + protected static $libHue = ['color']; protected function libHue($args) { @@ -5642,21 +6378,32 @@ protected function libComplement($args) return $this->adjustHsl($this->assertColor($args[0]), 1, 180); } - protected static $libInvert = ['color']; + protected static $libInvert = ['color', 'weight:1']; protected function libInvert($args) { - $value = $args[0]; + list($value, $weight) = $args; + + if (! isset($weight)) { + $weight = 1; + } else { + $weight = $this->coercePercent($weight); + } if ($value[0] === Type::T_NUMBER) { return null; } $color = $this->assertColor($value); - $color[1] = 255 - $color[1]; - $color[2] = 255 - $color[2]; - $color[3] = 255 - $color[3]; + $inverted = $color; + $inverted[1] = 255 - $inverted[1]; + $inverted[2] = 255 - $inverted[2]; + $inverted[3] = 255 - $inverted[3]; - return $color; + if ($weight < 1) { + return $this->libMix([$inverted, $color, [Type::T_NUMBER, $weight]]); + } + + return $inverted; } // increases opacity by amount @@ -5721,13 +6468,13 @@ protected function libQuote($args) return [Type::T_STRING, '"', [$value]]; } - protected static $libPercentage = ['value']; + protected static $libPercentage = ['number']; protected function libPercentage($args) { return new Node\Number($this->coercePercent($args[0]) * 100, '%'); } - protected static $libRound = ['value']; + protected static $libRound = ['number']; protected function libRound($args) { $num = $args[0]; @@ -5735,7 +6482,7 @@ protected function libRound($args) return new Node\Number(round($num[1]), $num[2]); } - protected static $libFloor = ['value']; + protected static $libFloor = ['number']; protected function libFloor($args) { $num = $args[0]; @@ -5743,7 +6490,7 @@ protected function libFloor($args) return new Node\Number(floor($num[1]), $num[2]); } - protected static $libCeil = ['value']; + protected static $libCeil = ['number']; protected function libCeil($args) { $num = $args[0]; @@ -5751,7 +6498,7 @@ protected function libCeil($args) return new Node\Number(ceil($num[1]), $num[2]); } - protected static $libAbs = ['value']; + protected static $libAbs = ['number']; protected function libAbs($args) { $num = $args[0]; @@ -5762,29 +6509,47 @@ protected function libAbs($args) protected function libMin($args) { $numbers = $this->getNormalizedNumbers($args); - $min = null; + $minOriginal = null; + $minNormalized = null; - foreach ($numbers as $key => $number) { - if (null === $min || $number[1] <= $min[1]) { - $min = [$key, $number[1]]; + foreach ($numbers as $key => $pair) { + list($original, $normalized) = $pair; + + if (\is_null($normalized) or \is_null($minNormalized)) { + if (\is_null($minOriginal) || $original[1] <= $minOriginal[1]) { + $minOriginal = $original; + $minNormalized = $normalized; + } + } elseif ($normalized[1] <= $minNormalized[1]) { + $minOriginal = $original; + $minNormalized = $normalized; } } - return $args[$min[0]]; + return $minOriginal; } protected function libMax($args) { $numbers = $this->getNormalizedNumbers($args); - $max = null; + $maxOriginal = null; + $maxNormalized = null; + + foreach ($numbers as $key => $pair) { + list($original, $normalized) = $pair; - foreach ($numbers as $key => $number) { - if (null === $max || $number[1] >= $max[1]) { - $max = [$key, $number[1]]; + if (\is_null($normalized) or \is_null($maxNormalized)) { + if (\is_null($maxOriginal) || $original[1] >= $maxOriginal[1]) { + $maxOriginal = $original; + $maxNormalized = $normalized; + } + } elseif ($normalized[1] >= $maxNormalized[1]) { + $maxOriginal = $original; + $maxNormalized = $normalized; } } - return $args[$max[0]]; + return $maxOriginal; } /** @@ -5796,9 +6561,9 @@ protected function libMax($args) */ protected function getNormalizedNumbers($args) { - $unit = null; + $unit = null; $originalUnit = null; - $numbers = []; + $numbers = []; foreach ($args as $key => $item) { if ($item[0] !== Type::T_NUMBER) { @@ -5808,15 +6573,15 @@ protected function getNormalizedNumbers($args) $number = $item->normalize(); - if (null === $unit) { + if (empty($unit)) { $unit = $number[2]; $originalUnit = $item->unitStr(); - } elseif ($number[1] && $unit !== $number[2]) { + } elseif ($number[1] && $unit !== $number[2] && ! empty($number[2])) { $this->throwError('Incompatible units: "%s" and "%s".', $originalUnit, $item->unitStr()); break; } - $numbers[$key] = $number; + $numbers[$key] = [$args[$key], empty($number[2]) ? null : $number]; } return $numbers; @@ -5825,21 +6590,21 @@ protected function getNormalizedNumbers($args) protected static $libLength = ['list']; protected function libLength($args) { - $list = $this->coerceList($args[0]); + $list = $this->coerceList($args[0], ',', true); - return count($list[2]); + return \count($list[2]); } //protected static $libListSeparator = ['list...']; protected function libListSeparator($args) { - if (count($args) > 1) { + if (\count($args) > 1) { return 'comma'; } $list = $this->coerceList($args[0]); - if (count($list[2]) <= 1) { + if (\count($list[2]) <= 1) { return 'space'; } @@ -5853,13 +6618,13 @@ protected function libListSeparator($args) protected static $libNth = ['list', 'n']; protected function libNth($args) { - $list = $this->coerceList($args[0]); + $list = $this->coerceList($args[0], ',', false); $n = $this->assertNumber($args[1]); if ($n > 0) { $n--; } elseif ($n < 0) { - $n += count($list[2]); + $n += \count($list[2]); } return isset($list[2][$n]) ? $list[2][$n] : static::$defaultValue; @@ -5874,7 +6639,7 @@ protected function libSetNth($args) if ($n > 0) { $n--; } elseif ($n < 0) { - $n += count($list[2]); + $n += \count($list[2]); } if (! isset($list[2][$n])) { @@ -5894,9 +6659,10 @@ protected function libMapGet($args) $map = $this->assertMap($args[0]); $key = $args[1]; - if (! is_null($key)) { + if (! \is_null($key)) { $key = $this->compileStringContent($this->coerceString($key)); - for ($i = count($map[1]) - 1; $i >= 0; $i--) { + + for ($i = \count($map[1]) - 1; $i >= 0; $i--) { if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) { return $map[2][$i]; } @@ -5930,7 +6696,7 @@ protected function libMapRemove($args) $map = $this->assertMap($args[0]); $key = $this->compileStringContent($this->coerceString($args[1])); - for ($i = count($map[1]) - 1; $i >= 0; $i--) { + for ($i = \count($map[1]) - 1; $i >= 0; $i--) { if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) { array_splice($map[1], $i, 1); array_splice($map[2], $i, 1); @@ -5946,7 +6712,7 @@ protected function libMapHasKey($args) $map = $this->assertMap($args[0]); $key = $this->compileStringContent($this->coerceString($args[1])); - for ($i = count($map[1]) - 1; $i >= 0; $i--) { + for ($i = \count($map[1]) - 1; $i >= 0; $i--) { if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) { return true; } @@ -5994,6 +6760,19 @@ protected function libKeywords($args) return [Type::T_MAP, $keys, $values]; } + protected static $libIsBracketed = ['list']; + protected function libIsBracketed($args) + { + $list = $args[0]; + $this->coerceList($list, ' '); + + if (! empty($list['enclosing']) && $list['enclosing'] === 'bracket') { + return true; + } + + return false; + } + protected function listSeparatorForJoin($list1, $sep) { if (! isset($sep)) { @@ -6012,16 +6791,51 @@ protected function listSeparatorForJoin($list1, $sep) } } - protected static $libJoin = ['list1', 'list2', 'separator:null']; + protected static $libJoin = ['list1', 'list2', 'separator:null', 'bracketed:auto']; protected function libJoin($args) { - list($list1, $list2, $sep) = $args; + list($list1, $list2, $sep, $bracketed) = $args; - $list1 = $this->coerceList($list1, ' '); - $list2 = $this->coerceList($list2, ' '); - $sep = $this->listSeparatorForJoin($list1, $sep); + $list1 = $this->coerceList($list1, ' ', true); + $list2 = $this->coerceList($list2, ' ', true); + $sep = $this->listSeparatorForJoin($list1, $sep); - return [Type::T_LIST, $sep, array_merge($list1[2], $list2[2])]; + if ($bracketed === static::$true) { + $bracketed = true; + } elseif ($bracketed === static::$false) { + $bracketed = false; + } elseif ($bracketed === [Type::T_KEYWORD, 'auto']) { + $bracketed = 'auto'; + } elseif ($bracketed === static::$null) { + $bracketed = false; + } else { + $bracketed = $this->compileValue($bracketed); + $bracketed = ! ! $bracketed; + + if ($bracketed === true) { + $bracketed = true; + } + } + + if ($bracketed === 'auto') { + $bracketed = false; + + if (! empty($list1['enclosing']) && $list1['enclosing'] === 'bracket') { + $bracketed = true; + } + } + + $res = [Type::T_LIST, $sep, array_merge($list1[2], $list2[2])]; + + if (isset($list1['enclosing'])) { + $res['enlcosing'] = $list1['enclosing']; + } + + if ($bracketed) { + $res['enclosing'] = 'bracket'; + } + + return $res; } protected static $libAppend = ['list', 'val', 'separator:null']; @@ -6029,16 +6843,21 @@ protected function libAppend($args) { list($list1, $value, $sep) = $args; - $list1 = $this->coerceList($list1, ' '); - $sep = $this->listSeparatorForJoin($list1, $sep); + $list1 = $this->coerceList($list1, ' ', true); + $sep = $this->listSeparatorForJoin($list1, $sep); + $res = [Type::T_LIST, $sep, array_merge($list1[2], [$value])]; + + if (isset($list1['enclosing'])) { + $res['enclosing'] = $list1['enclosing']; + } - return [Type::T_LIST, $sep, array_merge($list1[2], [$value])]; + return $res; } protected function libZip($args) { - foreach ($args as $arg) { - $this->assertList($arg); + foreach ($args as $key => $arg) { + $args[$key] = $this->coerceList($arg); } $lists = []; @@ -6166,7 +6985,7 @@ protected function libStrLength($args) $string = $this->coerceString($args[0]); $stringContent = $this->compileStringContent($string); - return new Node\Number(strlen($stringContent), ''); + return new Node\Number(\strlen($stringContent), ''); } protected static $libStrSlice = ['string', 'start-at', 'end-at:-1']; @@ -6201,7 +7020,7 @@ protected function libToLowerCase($args) $string = $this->coerceString($args[0]); $stringContent = $this->compileStringContent($string); - $string[2] = [function_exists('mb_strtolower') ? mb_strtolower($stringContent) : strtolower($stringContent)]; + $string[2] = [\function_exists('mb_strtolower') ? mb_strtolower($stringContent) : strtolower($stringContent)]; return $string; } @@ -6212,7 +7031,7 @@ protected function libToUpperCase($args) $string = $this->coerceString($args[0]); $stringContent = $this->compileStringContent($string); - $string[2] = [function_exists('mb_strtoupper') ? mb_strtoupper($stringContent) : strtoupper($stringContent)]; + $string[2] = [\function_exists('mb_strtoupper') ? mb_strtoupper($stringContent) : strtoupper($stringContent)]; return $string; } @@ -6224,7 +7043,7 @@ protected function libFeatureExists($args) $name = $this->compileStringContent($string); return $this->toBool( - array_key_exists($name, $this->registeredFeatures) ? $this->registeredFeatures[$name] : false + \array_key_exists($name, $this->registeredFeatures) ? $this->registeredFeatures[$name] : false ); } @@ -6248,7 +7067,7 @@ protected function libFunctionExists($args) // built-in functions $f = $this->getBuiltinFunction($name); - return $this->toBool(is_callable($f)); + return $this->toBool(\is_callable($f)); } protected static $libGlobalVariableExists = ['name']; @@ -6292,19 +7111,25 @@ protected function libCounter($args) return [Type::T_STRING, '', ['counter(' . implode(',', $list) . ')']]; } - protected static $libRandom = ['limit']; + protected static $libRandom = ['limit:1']; protected function libRandom($args) { if (isset($args[0])) { $n = $this->assertNumber($args[0]); if ($n < 1) { - $this->throwError("limit must be greater than or equal to 1"); + $this->throwError("\$limit must be greater than or equal to 1"); return null; } - return new Node\Number(mt_rand(1, $n), ''); + if ($n - \intval($n) > 0) { + $this->throwError("Expected \$limit to be an integer but got $n for `random`"); + + return null; + } + + return new Node\Number(mt_rand(1, \intval($n)), ''); } return new Node\Number(mt_rand(1, mt_getrandmax()), ''); @@ -6315,7 +7140,9 @@ protected function libUniqueId() static $id; if (! isset($id)) { - $id = mt_rand(0, pow(36, 8)); + $id = PHP_INT_SIZE === 4 + ? mt_rand(0, pow(36, 5)) . str_pad(mt_rand(0, pow(36, 5)) % 10000000, 7, '0', STR_PAD_LEFT) + : mt_rand(0, pow(36, 8)); } $id += mt_rand(0, 10) + 1; @@ -6323,14 +7150,46 @@ protected function libUniqueId() return [Type::T_STRING, '', ['u' . str_pad(base_convert($id, 10, 36), 8, '0', STR_PAD_LEFT)]]; } + protected function inspectFormatValue($value, $force_enclosing_display = false) + { + if ($value === static::$null) { + $value = [Type::T_KEYWORD, 'null']; + } + + $stringValue = [$value]; + + if ($value[0] === Type::T_LIST) { + if (end($value[2]) === static::$null) { + array_pop($value[2]); + $value[2][] = [Type::T_STRING, '', ['']]; + $force_enclosing_display = true; + } + + if (! empty($value['enclosing']) && + ($force_enclosing_display || + ($value['enclosing'] === 'bracket') || + ! \count($value[2])) + ) { + $value['enclosing'] = 'forced_'.$value['enclosing']; + $force_enclosing_display = true; + } + + foreach ($value[2] as $k => $listelement) { + $value[2][$k] = $this->inspectFormatValue($listelement, $force_enclosing_display); + } + + $stringValue = [$value]; + } + + return [Type::T_STRING, '', $stringValue]; + } + protected static $libInspect = ['value']; protected function libInspect($args) { - if ($args[0] === static::$null) { - return [Type::T_KEYWORD, 'null']; - } + $value = $args[0]; - return $args[0]; + return $this->inspectFormatValue($value); } /** @@ -6344,7 +7203,7 @@ protected function getSelectorArg($arg) { static $parser = null; - if (is_null($parser)) { + if (\is_null($parser)) { $parser = $this->parserFactory(__METHOD__); } @@ -6399,11 +7258,11 @@ protected function libIsSuperselector($args) protected function isSuperSelector($super, $sub) { // one and only one selector for each arg - if (! $super || count($super) !== 1) { + if (! $super || \count($super) !== 1) { $this->throwError("Invalid super selector for isSuperSelector()"); } - if (! $sub || count($sub) !== 1) { + if (! $sub || \count($sub) !== 1) { $this->throwError("Invalid sub selector for isSuperSelector()"); } @@ -6431,7 +7290,7 @@ function ($value, $key) use (&$compound) { $nextMustMatch = true; $i++; } else { - while ($i < count($sub) && ! $this->isSuperPart($node, $sub[$i])) { + while ($i < \count($sub) && ! $this->isSuperPart($node, $sub[$i])) { if ($nextMustMatch) { return false; } @@ -6439,7 +7298,7 @@ function ($value, $key) use (&$compound) { $i++; } - if ($i >= count($sub)) { + if ($i >= \count($sub)) { return false; } @@ -6464,11 +7323,11 @@ protected function isSuperPart($superParts, $subParts) $i = 0; foreach ($superParts as $superPart) { - while ($i < count($subParts) && $subParts[$i] !== $superPart) { + while ($i < \count($subParts) && $subParts[$i] !== $superPart) { $i++; } - if ($i >= count($subParts)) { + if ($i >= \count($subParts)) { return false; } @@ -6484,7 +7343,8 @@ protected function libSelectorAppend($args) // get the selector... list $args = reset($args); $args = $args[2]; - if (count($args) < 1) { + + if (\count($args) < 1) { $this->throwError("selector-append() needs at least 1 argument"); } @@ -6510,7 +7370,7 @@ protected function selectorAppend($selectors) $this->throwError("Invalid selector list in selector-append()"); } - while (count($selectors)) { + while (\count($selectors)) { $previousSelectors = array_pop($selectors); if (! $previousSelectors) { @@ -6550,8 +7410,8 @@ protected function libSelectorExtend($args) list($selectors, $extendee, $extender) = $args; $selectors = $this->getSelectorArg($selectors); - $extendee = $this->getSelectorArg($extendee); - $extender = $this->getSelectorArg($extender); + $extendee = $this->getSelectorArg($extendee); + $extender = $this->getSelectorArg($extender); if (! $selectors || ! $extendee || ! $extender) { $this->throwError("selector-extend() invalid arguments"); @@ -6567,8 +7427,8 @@ protected function libSelectorReplace($args) { list($selectors, $original, $replacement) = $args; - $selectors = $this->getSelectorArg($selectors); - $original = $this->getSelectorArg($original); + $selectors = $this->getSelectorArg($selectors); + $original = $this->getSelectorArg($original); $replacement = $this->getSelectorArg($replacement); if (! $selectors || ! $original || ! $replacement) { @@ -6611,12 +7471,12 @@ protected function extendOrReplaceSelectors($selectors, $extendee, $extender, $r $extended[] = $selector; } - $n = count($extended); + $n = \count($extended); $this->matchExtends($selector, $extended); // if didnt match, keep the original selector if we are in a replace operation - if ($replace and count($extended) === $n) { + if ($replace and \count($extended) === $n) { $extended[] = $selector; } } @@ -6633,13 +7493,14 @@ protected function libSelectorNest($args) // get the selector... list $args = reset($args); $args = $args[2]; - if (count($args) < 1) { + + if (\count($args) < 1) { $this->throwError("selector-nest() needs at least 1 argument"); } $selectorsMap = array_map([$this, 'getSelectorArg'], $args); - $envs = []; + foreach ($selectorsMap as $selectors) { $env = new Environment(); $env->selectors = $selectors; @@ -6647,8 +7508,8 @@ protected function libSelectorNest($args) $envs[] = $env; } - $envs = array_reverse($envs); - $env = $this->extractEnv($envs); + $envs = array_reverse($envs); + $env = $this->extractEnv($envs); $outputSelectors = $this->multiplySelectors($env); return $this->formatOutputSelector($outputSelectors); @@ -6691,22 +7552,23 @@ protected function libSelectorUnify($args) * * @param array $compound1 * @param array $compound2 + * * @return array|mixed */ protected function unifyCompoundSelectors($compound1, $compound2) { - if (! count($compound1)) { + if (! \count($compound1)) { return $compound2; } - if (! count($compound2)) { + if (! \count($compound2)) { return $compound1; } // check that last part are compatible $lastPart1 = array_pop($compound1); $lastPart2 = array_pop($compound2); - $last = $this->mergeParts($lastPart1, $lastPart2); + $last = $this->mergeParts($lastPart1, $lastPart2); if (! $last) { return [[]]; @@ -6716,7 +7578,7 @@ protected function unifyCompoundSelectors($compound1, $compound2) $unifiedSelectors = [$unifiedCompound]; // do the rest - while (count($compound1) || count($compound2)) { + while (\count($compound1) || \count($compound2)) { $part1 = end($compound1); $part2 = end($compound2); @@ -6729,6 +7591,7 @@ protected function unifyCompoundSelectors($compound1, $compound2) $c = $this->mergeParts($part1, $part2); $unifiedSelectors = $this->prependSelectors($unifiedSelectors, [$c]); + $part1 = $part2 = null; array_pop($compound1); @@ -6743,6 +7606,7 @@ protected function unifyCompoundSelectors($compound1, $compound2) $c = $this->mergeParts($part2, $part1); $unifiedSelectors = $this->prependSelectors($unifiedSelectors, [$c]); + $part1 = $part2 = null; array_pop($compound2); @@ -6754,9 +7618,9 @@ protected function unifyCompoundSelectors($compound1, $compound2) array_pop($compound1); array_pop($compound2); - $s = $this->prependSelectors($unifiedSelectors, [$part2]); + $s = $this->prependSelectors($unifiedSelectors, [$part2]); $new = array_merge($new, $this->prependSelectors($s, [$part1])); - $s = $this->prependSelectors($unifiedSelectors, [$part1]); + $s = $this->prependSelectors($unifiedSelectors, [$part1]); $new = array_merge($new, $this->prependSelectors($s, [$part2])); } elseif ($part1) { array_pop($compound1); @@ -6810,11 +7674,11 @@ protected function prependSelectors($selectors, $parts) protected function matchPartInCompound($part, $compound) { $partTag = $this->findTagName($part); - $before = $compound; - $after = []; + $before = $compound; + $after = []; // try to find a match by tag name first - while (count($before)) { + while (\count($before)) { $p = array_pop($before); if ($partTag && $partTag !== '*' && $partTag == $this->findTagName($p)) { @@ -6828,11 +7692,11 @@ protected function matchPartInCompound($part, $compound) $before = $compound; $after = []; - while (count($before)) { + while (\count($before)) { $p = array_pop($before); if ($this->checkCompatibleTags($partTag, $this->findTagName($p))) { - if (count(array_intersect($part, $p))) { + if (\count(array_intersect($part, $p))) { return [$before, $p, $after]; } } @@ -6857,7 +7721,7 @@ protected function mergeParts($parts1, $parts2) { $tag1 = $this->findTagName($parts1); $tag2 = $this->findTagName($parts2); - $tag = $this->checkCompatibleTags($tag1, $tag2); + $tag = $this->checkCompatibleTags($tag1, $tag2); // not compatible tags if ($tag === false) { @@ -6908,12 +7772,12 @@ protected function checkCompatibleTags($tag1, $tag2) $tags = array_unique($tags); $tags = array_filter($tags); - if (count($tags)>1) { + if (\count($tags) > 1) { $tags = array_diff($tags, ['*']); } // not compatible nodes - if (count($tags)>1) { + if (\count($tags) > 1) { return false; } @@ -6958,4 +7822,23 @@ protected function libSimpleSelectors($args) return [Type::T_LIST, ',', $listParts]; } + + protected static $libScssphpGlob = ['pattern']; + protected function libScssphpGlob($args) + { + $string = $this->coerceString($args[0]); + $pattern = $this->compileStringContent($string); + $matches = glob($pattern); + $listParts = []; + + foreach ($matches as $match) { + if (! is_file($match)) { + continue; + } + + $listParts[] = [Type::T_STRING, '"', [$match]]; + } + + return [Type::T_LIST, ',', $listParts]; + } } diff --git a/scssphp/scssphp/src/Compiler/Environment.php b/scssphp/scssphp/src/Compiler/Environment.php index 03eb86a5d..5dbe9f389 100644 --- a/scssphp/scssphp/src/Compiler/Environment.php +++ b/scssphp/scssphp/src/Compiler/Environment.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Exception/CompilerException.php b/scssphp/scssphp/src/Exception/CompilerException.php index a9d134fca..c91ec96a2 100644 --- a/scssphp/scssphp/src/Exception/CompilerException.php +++ b/scssphp/scssphp/src/Exception/CompilerException.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Exception/ParserException.php b/scssphp/scssphp/src/Exception/ParserException.php index 2fa12dd7a..62e9df460 100644 --- a/scssphp/scssphp/src/Exception/ParserException.php +++ b/scssphp/scssphp/src/Exception/ParserException.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Exception/RangeException.php b/scssphp/scssphp/src/Exception/RangeException.php index ee36c97e1..5f7537f9f 100644 --- a/scssphp/scssphp/src/Exception/RangeException.php +++ b/scssphp/scssphp/src/Exception/RangeException.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Exception/ServerException.php b/scssphp/scssphp/src/Exception/ServerException.php index d4a207aff..485334429 100644 --- a/scssphp/scssphp/src/Exception/ServerException.php +++ b/scssphp/scssphp/src/Exception/ServerException.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Formatter.php b/scssphp/scssphp/src/Formatter.php index 478aa6a56..eb09c394d 100644 --- a/scssphp/scssphp/src/Formatter.php +++ b/scssphp/scssphp/src/Formatter.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -81,6 +81,11 @@ abstract class Formatter */ protected $sourceMapGenerator; + /** + * @var string + */ + protected $strippedSemicolon; + /** * Initialize formatter * @@ -114,21 +119,19 @@ public function property($name, $value) } /** - * Strip semi-colon appended by property(); it's a separator, not a terminator + * Return custom property assignment + * differs in that you have to keep spaces in the value as is * * @api * - * @param array $lines + * @param string $name + * @param mixed $value + * + * @return string */ - public function stripSemicolon(&$lines) + public function customProperty($name, $value) { - if ($this->keepSemicolons) { - return; - } - - if (($count = count($lines)) && substr($lines[$count - 1], -1) === ';') { - $lines[$count - 1] = substr($lines[$count - 1], 0, -1); - } + return rtrim($name) . trim($this->assignSeparator) . $value . ';'; } /** @@ -139,8 +142,7 @@ public function stripSemicolon(&$lines) protected function blockLines(OutputBlock $block) { $inner = $this->indentStr(); - - $glue = $this->break . $inner; + $glue = $this->break . $inner; $this->write($inner . implode($glue, $block->lines)); @@ -207,6 +209,10 @@ protected function block(OutputBlock $block) if (! empty($block->selectors)) { $this->indentLevel--; + if (! $this->keepSemicolons) { + $this->strippedSemicolon = ''; + } + if (empty($block->children)) { $this->write($this->break); } @@ -217,8 +223,10 @@ protected function block(OutputBlock $block) /** * Test and clean safely empty children + * * @param \ScssPhp\ScssPhp\Formatter\OutputBlock $block - * @return bool + * + * @return boolean */ protected function testEmptyChildren($block) { @@ -228,14 +236,16 @@ protected function testEmptyChildren($block) foreach ($block->children as $k => &$child) { if (! $this->testEmptyChildren($child)) { $isEmpty = false; - } else { - if ($child->type === Type::T_MEDIA || $child->type === Type::T_DIRECTIVE) { - $child->children = []; - $child->selectors = null; - } + continue; + } + + if ($child->type === Type::T_MEDIA || $child->type === Type::T_DIRECTIVE) { + $child->children = []; + $child->selectors = null; } } } + return $isEmpty; } @@ -254,8 +264,8 @@ public function format(OutputBlock $block, SourceMapGenerator $sourceMapGenerato $this->sourceMapGenerator = null; if ($sourceMapGenerator) { - $this->currentLine = 1; - $this->currentColumn = 0; + $this->currentLine = 1; + $this->currentColumn = 0; $this->sourceMapGenerator = $sourceMapGenerator; } @@ -271,10 +281,32 @@ public function format(OutputBlock $block, SourceMapGenerator $sourceMapGenerato } /** + * Output content + * * @param string $str */ protected function write($str) { + if (! empty($this->strippedSemicolon)) { + echo $this->strippedSemicolon; + + $this->strippedSemicolon = ''; + } + + /* + * Maybe Strip semi-colon appended by property(); it's a separator, not a terminator + * will be striped for real before a closing, otherwise displayed unchanged starting the next write + */ + if (! $this->keepSemicolons && + $str && + (strpos($str, ';') !== false) && + (substr($str, -1) === ';') + ) { + $str = substr($str, 0, -1); + + $this->strippedSemicolon = ';'; + } + if ($this->sourceMapGenerator) { $this->sourceMapGenerator->addMapping( $this->currentLine, @@ -286,12 +318,12 @@ protected function write($str) ); $lines = explode("\n", $str); - $lineCount = count($lines); + $lineCount = \count($lines); $this->currentLine += $lineCount-1; $lastLine = array_pop($lines); - $this->currentColumn = ($lineCount === 1 ? $this->currentColumn : 0) + strlen($lastLine); + $this->currentColumn = ($lineCount === 1 ? $this->currentColumn : 0) + \strlen($lastLine); } echo $str; diff --git a/scssphp/scssphp/src/Formatter/Compact.php b/scssphp/scssphp/src/Formatter/Compact.php index 591f0c92e..a166ed9d9 100644 --- a/scssphp/scssphp/src/Formatter/Compact.php +++ b/scssphp/scssphp/src/Formatter/Compact.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Formatter/Compressed.php b/scssphp/scssphp/src/Formatter/Compressed.php index ec4722eaf..f400d92ab 100644 --- a/scssphp/scssphp/src/Formatter/Compressed.php +++ b/scssphp/scssphp/src/Formatter/Compressed.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Formatter/Crunched.php b/scssphp/scssphp/src/Formatter/Crunched.php index 51ccb516d..c2aea9906 100644 --- a/scssphp/scssphp/src/Formatter/Crunched.php +++ b/scssphp/scssphp/src/Formatter/Crunched.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Formatter/Debug.php b/scssphp/scssphp/src/Formatter/Debug.php index 94e70c815..6a2848d41 100644 --- a/scssphp/scssphp/src/Formatter/Debug.php +++ b/scssphp/scssphp/src/Formatter/Debug.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Formatter/Expanded.php b/scssphp/scssphp/src/Formatter/Expanded.php index 8eec47587..e3510fac9 100644 --- a/scssphp/scssphp/src/Formatter/Expanded.php +++ b/scssphp/scssphp/src/Formatter/Expanded.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -55,7 +55,7 @@ protected function blockLines(OutputBlock $block) foreach ($block->lines as $index => $line) { if (substr($line, 0, 2) === '/*') { - $block->lines[$index] = preg_replace('/(\r|\n)+/', $glue, $line); + $block->lines[$index] = preg_replace('/[\r\n]+/', $glue, $line); } } diff --git a/scssphp/scssphp/src/Formatter/Nested.php b/scssphp/scssphp/src/Formatter/Nested.php index 50a70ce6a..7179908c2 100644 --- a/scssphp/scssphp/src/Formatter/Nested.php +++ b/scssphp/scssphp/src/Formatter/Nested.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -58,29 +58,17 @@ protected function indentStr() protected function blockLines(OutputBlock $block) { $inner = $this->indentStr(); - - $glue = $this->break . $inner; + $glue = $this->break . $inner; foreach ($block->lines as $index => $line) { if (substr($line, 0, 2) === '/*') { - $block->lines[$index] = preg_replace('/(\r|\n)+/', $glue, $line); + $block->lines[$index] = preg_replace('/[\r\n]+/', $glue, $line); } } $this->write($inner . implode($glue, $block->lines)); } - protected function hasFlatChild($block) - { - foreach ($block->children as $child) { - if (empty($child->selectors)) { - return true; - } - } - - return false; - } - /** * {@inheritdoc} */ @@ -101,7 +89,7 @@ protected function block(OutputBlock $block) $previousHasSelector = false; } - $isMediaOrDirective = in_array($block->type, [Type::T_DIRECTIVE, Type::T_MEDIA]); + $isMediaOrDirective = \in_array($block->type, [Type::T_DIRECTIVE, Type::T_MEDIA]); $isSupport = ($block->type === Type::T_DIRECTIVE && $block->selectors && strpos(implode('', $block->selectors), '@supports') !== false); @@ -109,7 +97,7 @@ protected function block(OutputBlock $block) array_pop($depths); $this->depth--; - if (!$this->depth && ($block->depth <= 1 || (!$this->indentLevel && $block->type === Type::T_COMMENT)) && + if (! $this->depth && ($block->depth <= 1 || (! $this->indentLevel && $block->type === Type::T_COMMENT)) && (($block->selectors && ! $isMediaOrDirective) || $previousHasSelector) ) { $downLevel = $this->break; @@ -130,10 +118,12 @@ protected function block(OutputBlock $block) if ($block->depth > end($depths)) { if (! $previousEmpty || $this->depth < 1) { $this->depth++; + $depths[] = $block->depth; } else { // keep the current depth unchanged but take the block depth as a new reference for following blocks array_pop($depths); + $depths[] = $block->depth; } } @@ -170,15 +160,18 @@ protected function block(OutputBlock $block) } $this->blockLines($block); + $closeBlock = $this->break; } if (! empty($block->children)) { - if ($this->depth>0 && ($isMediaOrDirective || ! $this->hasFlatChild($block))) { + if ($this->depth > 0 && ($isMediaOrDirective || ! $this->hasFlatChild($block))) { array_pop($depths); + $this->depth--; $this->blockChildren($block); $this->depth++; + $depths[] = $block->depth; } else { $this->blockChildren($block); @@ -193,13 +186,19 @@ protected function block(OutputBlock $block) if (! empty($block->selectors)) { $this->indentLevel--; + if (! $this->keepSemicolons) { + $this->strippedSemicolon = ''; + } + $this->write($this->close); + $closeBlock = $this->break; if ($this->depth > 1 && ! empty($block->children)) { array_pop($depths); $this->depth--; } + if (! $isMediaOrDirective) { $previousHasSelector = true; } @@ -209,4 +208,22 @@ protected function block(OutputBlock $block) $this->write($this->break); } } + + /** + * Block has flat child + * + * @param \ScssPhp\ScssPhp\Formatter\OutputBlock $block + * + * @return boolean + */ + private function hasFlatChild($block) + { + foreach ($block->children as $child) { + if (empty($child->selectors)) { + return true; + } + } + + return false; + } } diff --git a/scssphp/scssphp/src/Formatter/OutputBlock.php b/scssphp/scssphp/src/Formatter/OutputBlock.php index 3e6fd9289..24841a591 100644 --- a/scssphp/scssphp/src/Formatter/OutputBlock.php +++ b/scssphp/scssphp/src/Formatter/OutputBlock.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Node.php b/scssphp/scssphp/src/Node.php index dab565a63..cab9a4b88 100644 --- a/scssphp/scssphp/src/Node.php +++ b/scssphp/scssphp/src/Node.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Node/Number.php b/scssphp/scssphp/src/Node/Number.php index 1e83bf8ce..4e6f66464 100644 --- a/scssphp/scssphp/src/Node/Number.php +++ b/scssphp/scssphp/src/Node/Number.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -31,14 +31,14 @@ class Number extends Node implements \ArrayAccess /** * @var integer */ - static public $precision = 10; + public static $precision = 10; /** * @see http://www.w3.org/TR/2012/WD-css3-values-20120308/ * * @var array */ - static protected $unitTable = [ + protected static $unitTable = [ 'in' => [ 'in' => 1, 'pc' => 6, @@ -64,8 +64,8 @@ class Number extends Node implements \ArrayAccess ], 'dpi' => [ 'dpi' => 1, - 'dpcm' => 2.54, - 'dppx' => 96, + 'dpcm' => 1/2.54, + 'dppx' => 1/96, ], ]; @@ -89,7 +89,7 @@ public function __construct($dimension, $initialUnit) { $this->type = Type::T_NUMBER; $this->dimension = $dimension; - $this->units = is_array($initialUnit) + $this->units = \is_array($initialUnit) ? $initialUnit : ($initialUnit ? [$initialUnit => 1] : []); @@ -110,11 +110,18 @@ public function coerce($units) $dimension = $this->dimension; - foreach (static::$unitTable['in'] as $unit => $conv) { - $from = isset($this->units[$unit]) ? $this->units[$unit] : 0; - $to = isset($units[$unit]) ? $units[$unit] : 0; - $factor = pow($conv, $from - $to); - $dimension /= $factor; + if (\count($units)) { + $baseUnit = array_keys($units); + $baseUnit = reset($baseUnit); + $baseUnit = $this->findBaseUnit($baseUnit); + if ($baseUnit && isset(static::$unitTable[$baseUnit])) { + foreach (static::$unitTable[$baseUnit] as $unit => $conv) { + $from = isset($this->units[$unit]) ? $this->units[$unit] : 0; + $to = isset($units[$unit]) ? $units[$unit] : 0; + $factor = pow($conv, $from - $to); + $dimension /= $factor; + } + } } return new Number($dimension, $units); @@ -130,7 +137,7 @@ public function normalize() $dimension = $this->dimension; $units = []; - $this->normalizeUnits($dimension, $units, 'in'); + $this->normalizeUnits($dimension, $units); return new Number($dimension, $units); } @@ -141,11 +148,11 @@ public function normalize() public function offsetExists($offset) { if ($offset === -3) { - return $this->sourceColumn !== null; + return ! \is_null($this->sourceColumn); } if ($offset === -2) { - return $this->sourceLine !== null; + return ! \is_null($this->sourceLine); } if ($offset === -1 || @@ -231,6 +238,35 @@ public function unitless() return ! array_sum($this->units); } + /** + * Test if a number can be normalized in a base unit + * ie if its units are homogeneous + * + * @return boolean + */ + public function isNormalizable() + { + if ($this->unitless()) { + return false; + } + + $baseUnit = null; + + foreach ($this->units as $unit => $exp) { + $b = $this->findBaseUnit($unit); + + if (\is_null($baseUnit)) { + $baseUnit = $b; + } + + if (\is_null($b) or $b !== $baseUnit) { + return false; + } + } + + return $baseUnit; + } + /** * Returns unit(s) as the product of numerator units divided by the product of denominator units * @@ -243,17 +279,17 @@ public function unitStr() foreach ($this->units as $unit => $unitSize) { if ($unitSize > 0) { - $numerators = array_pad($numerators, count($numerators) + $unitSize, $unit); + $numerators = array_pad($numerators, \count($numerators) + $unitSize, $unit); continue; } if ($unitSize < 0) { - $denominators = array_pad($denominators, count($denominators) + $unitSize, $unit); + $denominators = array_pad($denominators, \count($denominators) - $unitSize, $unit); continue; } } - return implode('*', $numerators) . (count($denominators) ? '/' . implode('*', $denominators) : ''); + return implode('*', $numerators) . (\count($denominators) ? '/' . implode('*', $denominators) : ''); } /** @@ -271,11 +307,11 @@ public function output(Compiler $compiler = null) return $unitSize; }); - if (count($units) > 1 && array_sum($units) === 0) { + if (\count($units) > 1 && array_sum($units) === 0) { $dimension = $this->dimension; $units = []; - $this->normalizeUnits($dimension, $units, 'in'); + $this->normalizeUnits($dimension, $units); $dimension = round($dimension, static::$precision); $units = array_filter($units, function ($unitSize) { @@ -285,12 +321,14 @@ public function output(Compiler $compiler = null) $unitSize = array_sum($units); - if ($compiler && ($unitSize > 1 || $unitSize < 0 || count($units) > 1)) { - $compiler->throwError((string) $dimension . $this->unitStr() . " isn't a valid CSS value."); + if ($compiler && ($unitSize > 1 || $unitSize < 0 || \count($units) > 1)) { + $this->units = $units; + $unit = $this->unitStr(); + } else { + reset($units); + $unit = key($units); } - reset($units); - $unit = key($units); $dimension = number_format($dimension, static::$precision, '.', ''); return (static::$precision ? rtrim(rtrim($dimension, '0'), '.') : $dimension) . $unit; @@ -311,13 +349,17 @@ public function __toString() * @param array $units * @param string $baseUnit */ - private function normalizeUnits(&$dimension, &$units, $baseUnit = 'in') + private function normalizeUnits(&$dimension, &$units, $baseUnit = null) { $dimension = $this->dimension; $units = []; foreach ($this->units as $unit => $exp) { - if (isset(static::$unitTable[$baseUnit][$unit])) { + if (! $baseUnit) { + $baseUnit = $this->findBaseUnit($unit); + } + + if ($baseUnit && isset(static::$unitTable[$baseUnit][$unit])) { $factor = pow(static::$unitTable[$baseUnit][$unit], $exp); $unit = $baseUnit; @@ -327,4 +369,22 @@ private function normalizeUnits(&$dimension, &$units, $baseUnit = 'in') $units[$unit] = $exp + (isset($units[$unit]) ? $units[$unit] : 0); } } + + /** + * Find the base unit family for a given unit + * + * @param string $unit + * + * @return string|null + */ + private function findBaseUnit($unit) + { + foreach (static::$unitTable as $baseUnit => $unitVariants) { + if (isset($unitVariants[$unit])) { + return $baseUnit; + } + } + + return null; + } } diff --git a/scssphp/scssphp/src/Parser.php b/scssphp/scssphp/src/Parser.php index 9b409e0b8..5083d5624 100644 --- a/scssphp/scssphp/src/Parser.php +++ b/scssphp/scssphp/src/Parser.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -65,12 +65,15 @@ class Parser private $inParens; private $eatWhiteDefault; private $discardComments; + private $allowVars; private $buffer; private $utf8; private $encoding; private $patternModifiers; private $commentsSeen; + private $cssOnly; + /** * Constructor * @@ -81,7 +84,7 @@ class Parser * @param string $encoding * @param \ScssPhp\ScssPhp\Cache $cache */ - public function __construct($sourceName, $sourceIndex = 0, $encoding = 'utf-8', $cache = null) + public function __construct($sourceName, $sourceIndex = 0, $encoding = 'utf-8', $cache = null, $cssOnly = false) { $this->sourceName = $sourceName ?: '(stdin)'; $this->sourceIndex = $sourceIndex; @@ -89,7 +92,9 @@ public function __construct($sourceName, $sourceIndex = 0, $encoding = 'utf-8', $this->utf8 = ! $encoding || strtolower($encoding) === 'utf-8'; $this->patternModifiers = $this->utf8 ? 'Aisu' : 'Ais'; $this->commentsSeen = []; - $this->discardComments = false; + $this->commentsSeen = []; + $this->allowVars = true; + $this->cssOnly = $cssOnly; if (empty(static::$operatorPattern)) { static::$operatorPattern = '([*\/%+-]|[!=]\=|\>\=?|\<\=\>|\<\=?|and|or)'; @@ -139,9 +144,13 @@ public function throwParseError($msg = 'parse error') : "$this->sourceName on line $line, at column $column"; if ($this->peek("(.*?)(\n|$)", $m, $this->count)) { + $this->restoreEncoding(); + throw new ParserException("$msg: failed at `$m[1]` $loc"); } + $this->restoreEncoding(); + throw new ParserException("$msg: $loc"); } @@ -164,7 +173,7 @@ public function parse($buffer) ]; $v = $this->cache->getCache("parse", $cacheKey, $parseOptions); - if (! is_null($v)) { + if (! \is_null($v)) { return $v; } } @@ -192,7 +201,7 @@ public function parse($buffer) ; } - if ($this->count !== strlen($this->buffer)) { + if ($this->count !== \strlen($this->buffer)) { $this->throwParseError(); } @@ -218,8 +227,8 @@ public function parse($buffer) * * @api * - * @param string $buffer - * @param string $out + * @param string $buffer + * @param string|array $out * * @return boolean */ @@ -245,8 +254,8 @@ public function parseValue($buffer, &$out) * * @api * - * @param string $buffer - * @param string $out + * @param string $buffer + * @param string|array $out * * @return boolean */ @@ -272,10 +281,10 @@ public function parseSelector($buffer, &$out) * * @api * - * @param string $buffer - * @param string $out + * @param string $buffer + * @param string|array $out * - * @return array + * @return boolean */ public function parseMediaQueryList($buffer, &$out) { @@ -287,7 +296,6 @@ public function parseMediaQueryList($buffer, &$out) $this->saveEncoding(); - $isMediaQuery = $this->mediaQueryList($out); $this->restoreEncoding(); @@ -348,9 +356,13 @@ protected function parseChunk() && $this->matchChar(')')) || true) && $this->matchChar('{', false) ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $atRoot = $this->pushSpecialBlock(Type::T_AT_ROOT, $s); $atRoot->selector = $selector; - $atRoot->with = $with; + $atRoot->with = $with; return true; } @@ -371,6 +383,10 @@ protected function parseChunk() ($this->argumentDef($args) || true) && $this->matchChar('{', false) ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $mixin = $this->pushSpecialBlock(Type::T_MIXIN, $s); $mixin->name = $mixinName; $mixin->args = $args; @@ -391,7 +407,17 @@ protected function parseChunk() ($this->end() || $this->matchChar('{') && $hasBlock = true)) || $this->matchChar('{') && $hasBlock = true) ) { - $child = [Type::T_INCLUDE, $mixinName, isset($argValues) ? $argValues : null, null, isset($argUsing) ? $argUsing : null]; + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + + $child = [ + Type::T_INCLUDE, + $mixinName, + isset($argValues) ? $argValues : null, + null, + isset($argUsing) ? $argUsing : null + ]; if (! empty($hasBlock)) { $include = $this->pushSpecialBlock(Type::T_INCLUDE, $s); @@ -409,6 +435,10 @@ protected function parseChunk() $this->valueList($importPath) && $this->end() ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_SCSSPHP_IMPORT_ONCE, $importPath], $s); return true; @@ -431,6 +461,10 @@ protected function parseChunk() $this->url($importPath) && $this->end() ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_IMPORT, $importPath], $s); return true; @@ -442,6 +476,10 @@ protected function parseChunk() $this->selectors($selectors) && $this->end() ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + // check for '!flag' $optional = $this->stripOptionalFlag($selectors); $this->append([Type::T_EXTEND, $selectors, $optional], $s); @@ -456,6 +494,10 @@ protected function parseChunk() $this->argumentDef($args) && $this->matchChar('{', false) ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $func = $this->pushSpecialBlock(Type::T_FUNCTION, $s); $func->name = $fnName; $func->args = $args; @@ -466,6 +508,10 @@ protected function parseChunk() $this->seek($s); if ($this->literal('@break', 6) && $this->end()) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_BREAK], $s); return true; @@ -474,6 +520,10 @@ protected function parseChunk() $this->seek($s); if ($this->literal('@continue', 9) && $this->end()) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_CONTINUE], $s); return true; @@ -482,6 +532,10 @@ protected function parseChunk() $this->seek($s); if ($this->literal('@return', 7) && ($this->valueList($retVal) || true) && $this->end()) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_RETURN, isset($retVal) ? $retVal : [Type::T_NULL]], $s); return true; @@ -495,6 +549,10 @@ protected function parseChunk() $this->valueList($list) && $this->matchChar('{', false) ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $each = $this->pushSpecialBlock(Type::T_EACH, $s); foreach ($varNames[2] as $varName) { @@ -512,6 +570,10 @@ protected function parseChunk() $this->expression($cond) && $this->matchChar('{', false) ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $while = $this->pushSpecialBlock(Type::T_WHILE, $s); $while->cond = $cond; @@ -529,10 +591,14 @@ protected function parseChunk() $this->expression($end) && $this->matchChar('{', false) ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $for = $this->pushSpecialBlock(Type::T_FOR, $s); - $for->var = $varName[1]; + $for->var = $varName[1]; $for->start = $start; - $for->end = $end; + $for->end = $end; $for->until = isset($forUntil); return true; @@ -541,8 +607,20 @@ protected function parseChunk() $this->seek($s); if ($this->literal('@if', 3) && $this->valueList($cond) && $this->matchChar('{', false)) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $if = $this->pushSpecialBlock(Type::T_IF, $s); - $if->cond = $cond; + + while ($cond[0] === Type::T_LIST + && ! empty($cond['enclosing']) + && $cond['enclosing'] === 'parent' + && \count($cond[2]) == 1) { + $cond = reset($cond[2]); + } + + $if->cond = $cond; $if->cases = []; return true; @@ -554,6 +632,10 @@ protected function parseChunk() $this->valueList($value) && $this->end() ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_DEBUG, $value], $s); return true; @@ -565,6 +647,10 @@ protected function parseChunk() $this->valueList($value) && $this->end() ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_WARN, $value], $s); return true; @@ -576,6 +662,10 @@ protected function parseChunk() $this->valueList($value) && $this->end() ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_ERROR, $value], $s); return true; @@ -583,14 +673,17 @@ protected function parseChunk() $this->seek($s); - #if ($this->literal('@content', 8)) - if ($this->literal('@content', 8) && ($this->end() || $this->matchChar('(') && - $this->argValues($argContent) && - $this->matchChar(')') && - $this->end())) { + $this->argValues($argContent) && + $this->matchChar(')') && + $this->end()) + ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $this->append([Type::T_MIXIN_CONTENT, isset($argContent) ? $argContent : null], $s); return true; @@ -646,9 +739,10 @@ protected function parseChunk() if ($this->literal('@supports', 9) && ($t1=$this->supportsQuery($supportQuery)) && - ($t2=$this->matchChar('{', false)) ) { + ($t2=$this->matchChar('{', false)) + ) { $directive = $this->pushSpecialBlock(Type::T_DIRECTIVE, $s); - $directive->name = 'supports'; + $directive->name = 'supports'; $directive->value = $supportQuery; return true; @@ -659,8 +753,7 @@ protected function parseChunk() // doesn't match built in directive, do generic one if ($this->matchChar('@', false) && $this->keyword($dirName) && - ($this->variable($dirValue) || $this->openString('{', $dirValue) || true) && - $this->matchChar('{', false) + $this->directiveValue($dirValue, '{') ) { if ($dirName === 'media') { $directive = $this->pushSpecialBlock(Type::T_MEDIA, $s); @@ -678,9 +771,67 @@ protected function parseChunk() $this->seek($s); + // maybe it's a generic blockless directive + if ($this->matchChar('@', false) && + $this->keyword($dirName) && + $this->directiveValue($dirValue) && + $this->end() + ) { + $this->append([Type::T_DIRECTIVE, [$dirName, $dirValue]], $s); + + return true; + } + + $this->seek($s); + return false; } + // custom properties : right part is static + if (($this->customProperty($name) || ($this->cssOnly && $this->propertyName($name))) && + $this->matchChar(':', false) + ) { + $start = $this->count; + + // but can be complex and finish with ; or } + foreach ([';','}'] as $ending) { + if ($this->openString($ending, $stringValue, '(', ')', false) && + $this->end() + ) { + $end = $this->count; + $value = $stringValue; + + // check if we have only a partial value due to nested [] or { } to take in account + $nestingPairs = [['[', ']'], ['{', '}']]; + + foreach ($nestingPairs as $nestingPair) { + $p = strpos($this->buffer, $nestingPair[0], $start); + + if ($p && $p < $end) { + $this->seek($start); + + if ($this->openString($ending, $stringValue, $nestingPair[0], $nestingPair[1], false) && + $this->end() && + $this->count > $end + ) { + $end = $this->count; + $value = $stringValue; + } + } + } + + $this->seek($end); + $this->append([Type::T_CUSTOM_PROPERTY, $name, $value], $s); + + return true; + } + } + + // TODO: output an error here if nothing found according to sass spec + } + + $this->seek($s); + // property shortcut // captures most properties before having to parse a selector if ($this->keyword($name, false) && @@ -702,6 +853,10 @@ protected function parseChunk() $this->valueList($value) && $this->end() ) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + // check for '!flag' $assignmentFlags = $this->stripAssignmentFlags($value); $this->append([Type::T_ASSIGN, $name, $value, $assignmentFlags], $s); @@ -718,11 +873,17 @@ protected function parseChunk() // opening css block if ($this->selectors($selectors) && $this->matchChar('{', false)) { + if ($this->cssOnly) { + if (! empty($this->env->parent)) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + } + $this->pushBlock($selectors, $s); if ($this->eatWhiteDefault) { $this->whitespace(); - $this->append(null); // collect comments at the begining if needed + $this->append(null); // collect comments at the beginning if needed } return true; @@ -744,6 +905,10 @@ protected function parseChunk() } if ($this->matchChar('{', false)) { + if ($this->cssOnly) { + $this->throwParseError("SCSS syntax not allowed in CSS file"); + } + $propBlock = $this->pushSpecialBlock(Type::T_NESTED_PROPERTY, $s); $propBlock->prefix = $name; $propBlock->hasValue = $foundSomething; @@ -764,7 +929,7 @@ protected function parseChunk() if ($this->matchChar('}', false)) { $block = $this->popBlock(); - if (!isset($block->type) || $block->type !== Type::T_IF) { + if (! isset($block->type) || $block->type !== Type::T_IF) { if ($this->env->parent) { $this->append(null); // collect comments before next statement if needed } @@ -836,7 +1001,7 @@ protected function pushBlock($selectors, $pos = 0) $this->env = $b; - // collect comments at the begining of a block if needed + // collect comments at the beginning of a block if needed if ($this->eatWhiteDefault) { $this->whitespace(); @@ -943,7 +1108,7 @@ protected function matchString(&$m, $delim) { $token = null; - $end = strlen($this->buffer); + $end = \strlen($this->buffer); // look for either ending delim, escape, or string interpolation foreach (['#{', '\\', $delim] as $lookahead) { @@ -965,7 +1130,7 @@ protected function matchString(&$m, $delim) $match, $token ]; - $this->count = $end + strlen($token); + $this->count = $end + \strlen($token); return true; } @@ -987,7 +1152,7 @@ protected function match($regex, &$out, $eatWhitespace = null) return false; } - $this->count += strlen($out[0]); + $this->count += \strlen($out[0]); if (! isset($eatWhitespace)) { $eatWhitespace = $this->eatWhiteDefault; @@ -1068,16 +1233,17 @@ protected function whitespace() if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { // comment that are kept in the output CSS $comment = []; - $endCommentCount = $this->count + strlen($m[1]); + $startCommentCount = $this->count; + $endCommentCount = $this->count + \strlen($m[1]); // find interpolations in comment $p = strpos($this->buffer, '#{', $this->count); while ($p !== false && $p < $endCommentCount) { - $c = substr($this->buffer, $this->count, $p - $this->count); - $comment[] = $c; + $c = substr($this->buffer, $this->count, $p - $this->count); + $comment[] = $c; $this->count = $p; - $out = null; + $out = null; if ($this->interpolation($out)) { // keep right spaces in the following string part @@ -1089,7 +1255,7 @@ protected function whitespace() $out[3] = ''; } - $comment[] = $out; + $comment[] = [Type::T_COMMENT, substr($this->buffer, $p, $this->count - $p), $out]; } else { $comment[] = substr($this->buffer, $this->count, 2); @@ -1107,14 +1273,15 @@ protected function whitespace() $this->appendComment([Type::T_COMMENT, $c]); } else { $comment[] = $c; - $this->appendComment([Type::T_COMMENT, [Type::T_STRING, '', $comment]]); + $staticComment = substr($this->buffer, $startCommentCount, $endCommentCount - $startCommentCount); + $this->appendComment([Type::T_COMMENT, $staticComment, [Type::T_STRING, '', $comment]]); } - $this->commentsSeen[$this->count] = true; + $this->commentsSeen[$startCommentCount] = true; $this->count = $endCommentCount; } else { // comment that are ignored and not kept in the output css - $this->count += strlen($m[0]); + $this->count += \strlen($m[0]); } $gotWhite = true; @@ -1131,8 +1298,23 @@ protected function whitespace() protected function appendComment($comment) { if (! $this->discardComments) { - if ($comment[0] === Type::T_COMMENT && is_string($comment[1])) { - $comment[1] = substr(preg_replace(['/^\s+/m', '/^(.)/m'], ['', ' \1'], $comment[1]), 1); + if ($comment[0] === Type::T_COMMENT) { + if (\is_string($comment[1])) { + $comment[1] = substr(preg_replace(['/^\s+/m', '/^(.)/m'], ['', ' \1'], $comment[1]), 1); + } + + if (isset($comment[2]) and \is_array($comment[2]) and $comment[2][0] === Type::T_STRING) { + foreach ($comment[2][2] as $k => $v) { + if (\is_string($v)) { + $p = strpos($v, "\n"); + + if ($p !== false) { + $comment[2][2][$k] = substr($v, 0, $p + 1) + . preg_replace(['/^\s+/m', '/^(.)/m'], ['', ' \1'], substr($v, $p+1)); + } + } + } + } } $this->env->comments[] = $comment; @@ -1147,8 +1329,8 @@ protected function appendComment($comment) */ protected function append($statement, $pos = null) { - if (! is_null($statement)) { - if ($pos !== null) { + if (! \is_null($statement)) { + if (! \is_null($pos)) { list($line, $column) = $this->getSourcePosition($pos); $statement[static::SOURCE_LINE] = $line; @@ -1174,7 +1356,7 @@ protected function append($statement, $pos = null) */ protected function last() { - $i = count($this->env->children) - 1; + $i = \count($this->env->children) - 1; if (isset($this->env->children[$i])) { return $this->env->children[$i]; @@ -1221,7 +1403,7 @@ protected function mediaQuery(&$out) $media = [Type::T_LIST, '', []]; foreach ((array) $mediaType as $type) { - if (is_array($type)) { + if (\is_array($type)) { $media[2][] = $type; } else { $media[2][] = [Type::T_KEYWORD, $type]; @@ -1235,7 +1417,7 @@ protected function mediaQuery(&$out) if (empty($parts) || $this->literal('and', 3)) { $this->genericList($expressions, 'mediaExpression', 'and', false); - if (is_array($expressions)) { + if (\is_array($expressions)) { $parts = array_merge($parts, $expressions[2]); } } @@ -1260,12 +1442,14 @@ protected function supportsQuery(&$out) $s = $this->count; $not = false; + if (($this->literal('not', 3) && ($not = true) || true) && $this->matchChar('(') && ($this->expression($property)) && $this->literal(': ', 2) && $this->valueList($value) && - $this->matchChar(')')) { + $this->matchChar(')') + ) { $support = [Type::T_STRING, '', [[Type::T_KEYWORD, ($not ? 'not ' : '') . '(']]]; $support[2][] = $property; $support[2][] = [Type::T_KEYWORD, ': ']; @@ -1280,7 +1464,8 @@ protected function supportsQuery(&$out) if ($this->matchChar('(') && $this->supportsQuery($subQuery) && - $this->matchChar(')')) { + $this->matchChar(')') + ) { $parts[] = [Type::T_STRING, '', [[Type::T_KEYWORD, '('], $subQuery, [Type::T_KEYWORD, ')']]]; $s = $this->count; } else { @@ -1288,7 +1473,8 @@ protected function supportsQuery(&$out) } if ($this->literal('not', 3) && - $this->supportsQuery($subQuery)) { + $this->supportsQuery($subQuery) + ) { $parts[] = [Type::T_STRING, '', [[Type::T_KEYWORD, 'not '], $subQuery]]; $s = $this->count; } else { @@ -1297,21 +1483,26 @@ protected function supportsQuery(&$out) if ($this->literal('selector(', 9) && $this->selector($selector) && - $this->matchChar(')')) { + $this->matchChar(')') + ) { $support = [Type::T_STRING, '', [[Type::T_KEYWORD, 'selector(']]]; $selectorList = [Type::T_LIST, '', []]; + foreach ($selector as $sc) { $compound = [Type::T_STRING, '', []]; + foreach ($sc as $scp) { - if (is_array($scp)) { + if (\is_array($scp)) { $compound[2][] = $scp; } else { $compound[2][] = [Type::T_KEYWORD, $scp]; } } + $selectorList[2][] = $compound; } + $support[2][] = $selectorList; $support[2][] = [Type::T_KEYWORD, ')']; $parts[] = $support; @@ -1330,6 +1521,7 @@ protected function supportsQuery(&$out) if ($this->literal('and', 3) && $this->genericList($expressions, 'supportsQuery', ' and', false)) { array_unshift($expressions[2], [Type::T_STRING, '', $parts]); + $parts = [$expressions]; $s = $this->count; } else { @@ -1339,17 +1531,20 @@ protected function supportsQuery(&$out) if ($this->literal('or', 2) && $this->genericList($expressions, 'supportsQuery', ' or', false)) { array_unshift($expressions[2], [Type::T_STRING, '', $parts]); + $parts = [$expressions]; $s = $this->count; } else { $this->seek($s); } - if (count($parts)) { + if (\count($parts)) { if ($this->eatWhiteDefault) { $this->whitespace(); } + $out = [Type::T_STRING, '', $parts]; + return true; } @@ -1421,6 +1616,7 @@ protected function argValue(&$out) if (! $this->variable($keyword) || ! $this->matchChar(':')) { $this->seek($s); + $keyword = null; } @@ -1440,6 +1636,63 @@ protected function argValue(&$out) return false; } + /** + * Parse directive value list that considers $vars as keyword + * + * @param array $out + * @param boolean|string $endChar + * + * @return boolean + */ + protected function directiveValue(&$out, $endChar = false) + { + $s = $this->count; + + if ($this->variable($out)) { + if ($endChar && $this->matchChar($endChar, false)) { + return true; + } + + if (! $endChar && $this->end()) { + return true; + } + } + + $this->seek($s); + + if ($endChar and $this->openString($endChar, $out)) { + if ($this->matchChar($endChar, false)) { + return true; + } + } + + $this->seek($s); + + $allowVars = $this->allowVars; + $this->allowVars = false; + + $res = $this->genericList($out, 'spaceList', ','); + $this->allowVars = $allowVars; + + if ($res) { + if ($endChar && $this->matchChar($endChar, false)) { + return true; + } + + if (! $endChar && $this->end()) { + return true; + } + } + + $this->seek($s); + + if ($endChar && $this->matchChar($endChar, false)) { + return true; + } + + return false; + } + /** * Parse comma separated value list * @@ -1453,6 +1706,7 @@ protected function valueList(&$out) $this->discardComments = true; $res = $this->genericList($out, 'spaceList', ','); $this->discardComments = $discardComments; + return $res; } @@ -1480,17 +1734,20 @@ protected function spaceList(&$out) */ protected function genericList(&$out, $parseItem, $delim = '', $flatten = true) { - $s = $this->count; + $s = $this->count; $items = []; $value = null; while ($this->$parseItem($value)) { + $trailing_delim = false; $items[] = $value; if ($delim) { - if (! $this->literal($delim, strlen($delim))) { + if (! $this->literal($delim, \strlen($delim))) { break; } + + $trailing_delim = true; } } @@ -1500,7 +1757,11 @@ protected function genericList(&$out, $parseItem, $delim = '', $flatten = true) return false; } - if ($flatten && count($items) === 1) { + if ($trailing_delim) { + $items[] = [Type::T_NULL]; + } + + if ($flatten && \count($items) === 1) { $out = $items[0]; } else { $out = [Type::T_LIST, $delim, $items]; @@ -1512,46 +1773,65 @@ protected function genericList(&$out, $parseItem, $delim = '', $flatten = true) /** * Parse expression * - * @param array $out + * @param array $out + * @param boolean $listOnly + * @param boolean $lookForExp * * @return boolean */ - protected function expression(&$out) + protected function expression(&$out, $listOnly = false, $lookForExp = true) { $s = $this->count; $discard = $this->discardComments; $this->discardComments = true; + $allowedTypes = ($listOnly ? [Type::T_LIST] : [Type::T_LIST, Type::T_MAP]); if ($this->matchChar('(')) { - if ($this->parenExpression($out, $s, ")")) { + if ($this->enclosedExpression($lhs, $s, ")", $allowedTypes)) { + if ($lookForExp) { + $out = $this->expHelper($lhs, 0); + } else { + $out = $lhs; + } + $this->discardComments = $discard; + return true; } $this->seek($s); } - if ($this->matchChar('[')) { - if ($this->parenExpression($out, $s, "]", [Type::T_LIST, Type::T_KEYWORD])) { - if ($out[0] !== Type::T_LIST && $out[0] !== Type::T_MAP) { - $out = [Type::T_STRING, '', [ '[', $out, ']' ]]; + if (\in_array(Type::T_LIST, $allowedTypes) && $this->matchChar('[')) { + if ($this->enclosedExpression($lhs, $s, "]", [Type::T_LIST])) { + if ($lookForExp) { + $out = $this->expHelper($lhs, 0); + } else { + $out = $lhs; } $this->discardComments = $discard; + return true; } $this->seek($s); } - if ($this->value($lhs)) { - $out = $this->expHelper($lhs, 0); + if (! $listOnly && $this->value($lhs)) { + if ($lookForExp) { + $out = $this->expHelper($lhs, 0); + } else { + $out = $lhs; + } $this->discardComments = $discard; + return true; } $this->discardComments = $discard; + return false; } @@ -1565,21 +1845,48 @@ protected function expression(&$out) * * @return boolean */ - protected function parenExpression(&$out, $s, $closingParen = ")", $allowedTypes = [Type::T_LIST, Type::T_MAP]) + protected function enclosedExpression(&$out, $s, $closingParen = ")", $allowedTypes = [Type::T_LIST, Type::T_MAP]) { - if ($this->matchChar($closingParen)) { + if ($this->matchChar($closingParen) && \in_array(Type::T_LIST, $allowedTypes)) { $out = [Type::T_LIST, '', []]; + switch ($closingParen) { + case ")": + $out['enclosing'] = 'parent'; // parenthesis list + break; + + case "]": + $out['enclosing'] = 'bracket'; // bracketed list + break; + } + return true; } - if ($this->valueList($out) && $this->matchChar($closingParen) && in_array($out[0], $allowedTypes)) { + if ($this->valueList($out) && $this->matchChar($closingParen) && + \in_array($out[0], [Type::T_LIST, Type::T_KEYWORD]) && + \in_array(Type::T_LIST, $allowedTypes) + ) { + if ($out[0] !== Type::T_LIST || ! empty($out['enclosing'])) { + $out = [Type::T_LIST, '', [$out]]; + } + + switch ($closingParen) { + case ")": + $out['enclosing'] = 'parent'; // parenthesis list + break; + + case "]": + $out['enclosing'] = 'bracket'; // bracketed list + break; + } + return true; } $this->seek($s); - if (in_array(Type::T_MAP, $allowedTypes) && $this->map($out)) { + if (\in_array(Type::T_MAP, $allowedTypes) && $this->map($out)) { return true; } @@ -1617,7 +1924,7 @@ protected function expHelper($lhs, $minP) break; } - if (! $this->value($rhs)) { + if (! $this->value($rhs) && ! $this->expression($rhs, true, false)) { break; } @@ -1708,28 +2015,53 @@ protected function value(&$out) if ($char === '+') { $this->count++; + $follow_white = $this->whitespace(); + if ($this->value($inner)) { $out = [Type::T_UNARY, '+', $inner, $this->inParens]; return true; } - $this->count--; + if ($follow_white) { + $out = [Type::T_KEYWORD, $char]; + return true; + } + + $this->seek($s); return false; } // negation if ($char === '-') { + if ($this->customProperty($out)) { + return true; + } + $this->count++; + $follow_white = $this->whitespace(); + if ($this->variable($inner) || $this->unit($inner) || $this->parenValue($inner)) { $out = [Type::T_UNARY, '-', $inner, $this->inParens]; return true; } - $this->count--; + if ($this->keyword($inner) && ! $this->func($inner, $out)) { + $out = [Type::T_UNARY, '-', $inner, $this->inParens]; + + return true; + } + + if ($follow_white) { + $out = [Type::T_KEYWORD, $char]; + + return true; + } + + $this->seek($s); } // paren @@ -1741,6 +2073,16 @@ protected function value(&$out) if ($this->interpolation($out) || $this->color($out)) { return true; } + + $this->count++; + + if ($this->keyword($keyword)) { + $out = [Type::T_KEYWORD, "#" . $keyword]; + + return true; + } + + $this->count--; } if ($this->matchChar('&', true)) { @@ -1768,6 +2110,7 @@ protected function value(&$out) // unicode range with wildcards if ($this->literal('U+', 2) && $this->match('([0-9A-F]+\?*)(-([0-9A-F]+))?', $m, false)) { $out = [Type::T_KEYWORD, 'U+' . $m[0]]; + return true; } @@ -1985,6 +2328,7 @@ protected function argumentDef(&$out) } $arg[2] = true; + $this->seek($sss); } else { $this->seek($ss); @@ -2057,55 +2401,18 @@ protected function map(&$out) */ protected function color(&$out) { - $color = [Type::T_COLOR]; - $s = $this->count; + $s = $this->count; if ($this->match('(#([0-9a-f]+))', $m)) { - $nofValues = strlen($m[2]); - $hasAlpha = $nofValues === 4 || $nofValues === 8; - $channels = $hasAlpha ? [4, 3, 2, 1] : [3, 2, 1]; - - switch ($nofValues) { - case 3: - case 4: - $num = hexdec($m[2]); - - foreach ($channels as $i) { - $t = $num & 0xf; - $color[$i] = $t << 4 | $t; - $num >>= 4; - } - - break; + if (\in_array(\strlen($m[2]), [3,4,6,8])) { + $out = [Type::T_KEYWORD, $m[0]]; - case 6: - case 8: - $num = hexdec($m[2]); - - foreach ($channels as $i) { - $color[$i] = $num & 0xff; - $num >>= 8; - } - - break; - - default: - $this->seek($s); - - return false; - } - - if ($hasAlpha) { - if ($color[4] === 255) { - $color[4] = 1; // fully opaque - } else { - $color[4] = round($color[4] / 255, 3); - } + return true; } - $out = $color; + $this->seek($s); - return true; + return false; } return false; @@ -2123,7 +2430,7 @@ protected function unit(&$unit) $s = $this->count; if ($this->match('([0-9]*(\.)?[0-9]+)([%a-zA-Z]+)?', $m, false)) { - if (strlen($this->buffer) === $this->count || ! ctype_digit($this->buffer[$this->count])) { + if (\strlen($this->buffer) === $this->count || ! ctype_digit($this->buffer[$this->count])) { $this->whitespace(); $unit = new Node\Number($m[1], empty($m[3]) ? '' : $m[3]); @@ -2167,13 +2474,13 @@ protected function string(&$out) } if ($m[2] === '#{') { - $this->count -= strlen($m[2]); + $this->count -= \strlen($m[2]); if ($this->interpolation($inter, false)) { $content[] = $inter; $hasInterpolation = true; } else { - $this->count += strlen($m[2]); + $this->count += \strlen($m[2]); $content[] = '#{'; // ignore it } } elseif ($m[2] === '\\') { @@ -2184,23 +2491,23 @@ protected function string(&$out) } elseif ($this->literal("\\", 1, false)) { $content[] = $m[2] . "\\"; } elseif ($this->literal("\r\n", 2, false) || - $this->matchChar("\r", false) || - $this->matchChar("\n", false) || - $this->matchChar("\f", false) + $this->matchChar("\r", false) || + $this->matchChar("\n", false) || + $this->matchChar("\f", false) ) { // this is a continuation escaping, to be ignored } else { $content[] = $m[2]; } } else { - $this->count -= strlen($delim); + $this->count -= \strlen($delim); break; // delim } } $this->eatWhiteDefault = $oldWhite; - if ($this->literal($delim, strlen($delim))) { + if ($this->literal($delim, \strlen($delim))) { if ($hasInterpolation) { $delim = '"'; @@ -2272,18 +2579,27 @@ protected function mixedKeyword(&$out, $restricted = false) /** * Parse an unbounded string stopped by $end * - * @param string $end - * @param array $out - * @param string $nestingOpen + * @param string $end + * @param array $out + * @param string $nestingOpen + * @param string $nestingClose + * @param boolean $trimEnd * * @return boolean */ - protected function openString($end, &$out, $nestingOpen = null) + protected function openString($end, &$out, $nestingOpen = null, $nestingClose = null, $trimEnd = true) { $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; - $patt = '(.*?)([\'"]|#\{|' . $this->pregQuote($end) . '|' . static::$commentPattern . ')'; + if ($nestingOpen && ! $nestingClose) { + $nestingClose = $end; + } + + $patt = '(.*?)([\'"]|#\{|' + . $this->pregQuote($end) . '|' + . (($nestingClose && $nestingClose !== $end) ? $this->pregQuote($nestingClose) . '|' : '') + . static::$commentPattern . ')'; $nestingLevel = 0; @@ -2300,12 +2616,16 @@ protected function openString($end, &$out, $nestingOpen = null) $tok = $m[2]; - $this->count-= strlen($tok); + $this->count-= \strlen($tok); - if ($tok === $end && ! $nestingLevel--) { + if ($tok === $end && ! $nestingLevel) { break; } + if ($tok === $nestingClose) { + $nestingLevel--; + } + if (($tok === "'" || $tok === '"') && $this->string($str)) { $content[] = $str; continue; @@ -2317,18 +2637,18 @@ protected function openString($end, &$out, $nestingOpen = null) } $content[] = $tok; - $this->count+= strlen($tok); + $this->count+= \strlen($tok); } $this->eatWhiteDefault = $oldWhite; - if (! $content) { + if (! $content || $tok !== $end) { return false; } // trim the end - if (is_string(end($content))) { - $content[count($content) - 1] = rtrim(end($content)); + if ($trimEnd && \is_string(end($content))) { + $content[\count($content) - 1] = rtrim(end($content)); } $out = [Type::T_STRING, '', $content]; @@ -2339,14 +2659,16 @@ protected function openString($end, &$out, $nestingOpen = null) /** * Parser interpolation * - * @param array $out - * @param boolean $lookWhite save information about whitespace before and after + * @param string|array $out + * @param boolean $lookWhite save information about whitespace before and after * * @return boolean */ protected function interpolation(&$out, $lookWhite = true) { $oldWhite = $this->eatWhiteDefault; + $allowVars = $this->allowVars; + $this->allowVars = true; $this->eatWhiteDefault = true; $s = $this->count; @@ -2366,6 +2688,7 @@ protected function interpolation(&$out, $lookWhite = true) } $this->eatWhiteDefault = $oldWhite; + $this->allowVars = $allowVars; if ($this->eatWhiteDefault) { $this->whitespace(); @@ -2377,6 +2700,7 @@ protected function interpolation(&$out, $lookWhite = true) $this->seek($s); $this->eatWhiteDefault = $oldWhite; + $this->allowVars = $allowVars; return false; } @@ -2422,16 +2746,10 @@ protected function propertyName(&$out) } // match comment hack - if (preg_match( - static::$whitePattern, - $this->buffer, - $m, - null, - $this->count - )) { + if (preg_match(static::$whitePattern, $this->buffer, $m, null, $this->count)) { if (! empty($m[0])) { $parts[] = $m[0]; - $this->count += strlen($m[0]); + $this->count += \strlen($m[0]); } } @@ -2443,12 +2761,67 @@ protected function propertyName(&$out) } /** - * Parse comma separated selector list + * Parse custom property name (as an array of parts or a string) * * @param array $out * * @return boolean */ + protected function customProperty(&$out) + { + $s = $this->count; + + if (! $this->literal('--', 2, false)) { + return false; + } + + $parts = ['--']; + + $oldWhite = $this->eatWhiteDefault; + $this->eatWhiteDefault = false; + + for (;;) { + if ($this->interpolation($inter)) { + $parts[] = $inter; + continue; + } + + if ($this->variable($var)) { + $parts[] = $var; + continue; + } + + if ($this->keyword($text)) { + $parts[] = $text; + continue; + } + + break; + } + + $this->eatWhiteDefault = $oldWhite; + + if (\count($parts) == 1) { + $this->seek($s); + + return false; + } + + $this->whitespace(); // get any extra whitespace + + $out = [Type::T_STRING, '', $parts]; + + return true; + } + + /** + * Parse comma separated selector list + * + * @param array $out + * @param boolean $subSelector + * + * @return boolean + */ protected function selectors(&$out, $subSelector = false) { $s = $this->count; @@ -2480,7 +2853,8 @@ protected function selectors(&$out, $subSelector = false) /** * Parse whitespace separated selector list * - * @param array $out + * @param array $out + * @param boolean $subSelector * * @return boolean */ @@ -2490,12 +2864,13 @@ protected function selector(&$out, $subSelector = false) for (;;) { $s = $this->count; + if ($this->match('[>+~]+', $m, true)) { - if ($subSelector && is_string($subSelector) && strpos($subSelector, 'nth-') === 0 - && $m[0] === '+' && $this->match("(\d+|n\b)", $counter)) { + if ($subSelector && \is_string($subSelector) && strpos($subSelector, 'nth-') === 0 && + $m[0] === '+' && $this->match("(\d+|n\b)", $counter) + ) { $this->seek($s); - } - else { + } else { $selector[] = [$m[0]]; continue; } @@ -2531,7 +2906,8 @@ protected function selector(&$out, $subSelector = false) * div[yes=no]#something.hello.world:nth-child(-2n+1)%placeholder * }} * - * @param array $out + * @param array $out + * @param boolean $subSelector * * @return boolean */ @@ -2631,12 +3007,13 @@ protected function selectorSingle(&$out, $subSelector = false) if ($nameParts === ['not'] || $nameParts === ['is'] || $nameParts === ['has'] || $nameParts === ['where'] || + $nameParts === ['slotted'] || $nameParts === ['nth-child'] || $nameParts == ['nth-last-child'] || $nameParts === ['nth-of-type'] || $nameParts == ['nth-last-of-type'] ) { if ($this->matchChar('(', true) && - ($this->selectors($subs, reset($nameParts)) || true) && - $this->matchChar(')') + ($this->selectors($subs, reset($nameParts)) || true) && + $this->matchChar(')') ) { $parts[] = '('; @@ -2645,11 +3022,13 @@ protected function selectorSingle(&$out, $subSelector = false) foreach ($ps as &$p) { $parts[] = $p; } - if (count($sub) && reset($sub)) { + + if (\count($sub) && reset($sub)) { $parts[] = ' '; } } - if (count($subs) && reset($subs)) { + + if (\count($subs) && reset($subs)) { $parts[] = ', '; } } @@ -2660,8 +3039,8 @@ protected function selectorSingle(&$out, $subSelector = false) } } else { if ($this->matchChar('(') && - ($this->openString(')', $str, '(') || true) && - $this->matchChar(')') + ($this->openString(')', $str, '(') || true) && + $this->matchChar(')') ) { $parts[] = '('; @@ -2682,7 +3061,7 @@ protected function selectorSingle(&$out, $subSelector = false) $this->seek($s); // 2n+1 - if ($subSelector && is_string($subSelector) && strpos($subSelector, 'nth-') === 0) { + if ($subSelector && \is_string($subSelector) && strpos($subSelector, 'nth-') === 0) { if ($this->match("(\s*(\+\s*|\-\s*)?(\d+|n|\d+n))+", $counter)) { $parts[] = $counter[0]; //$parts[] = str_replace(' ', '', $counter[0]); @@ -2747,7 +3126,11 @@ protected function variable(&$out) $s = $this->count; if ($this->matchChar('$', false) && $this->keyword($name)) { - $out = [Type::T_VARIABLE, $name]; + if ($this->allowVars) { + $out = [Type::T_VARIABLE, $name]; + } else { + $out = [Type::T_KEYWORD, '$' . $name]; + } return true; } @@ -2794,7 +3177,7 @@ protected function restrictedKeyword(&$word, $eatWhitespace = null) { $s = $this->count; - if ($this->keyword($word, $eatWhitespace) && (ord($word[0]) > 57 || ord($word[0]) < 48)) { + if ($this->keyword($word, $eatWhitespace) && (\ord($word[0]) > 57 || \ord($word[0]) < 48)) { return true; } @@ -2806,7 +3189,7 @@ protected function restrictedKeyword(&$word, $eatWhitespace = null) /** * Parse a placeholder * - * @param string $placeholder + * @param string|array $placeholder * * @return boolean */ @@ -2822,6 +3205,7 @@ protected function placeholder(&$placeholder) return true; } + if ($this->interpolation($placeholder)) { return true; } @@ -2858,7 +3242,7 @@ protected function end() return true; } - if ($this->count === strlen($this->buffer) || $this->buffer[$this->count] === '}') { + if ($this->count === \strlen($this->buffer) || $this->buffer[$this->count] === '}') { // if there is end of file or a closing block next then we don't need a ; return true; } @@ -2877,18 +3261,15 @@ protected function stripAssignmentFlags(&$value) { $flags = []; - for ($token = &$value; $token[0] === Type::T_LIST && ($s = count($token[2])); $token = &$lastNode) { + for ($token = &$value; $token[0] === Type::T_LIST && ($s = \count($token[2])); $token = &$lastNode) { $lastNode = &$token[2][$s - 1]; - while ($lastNode[0] === Type::T_KEYWORD && in_array($lastNode[1], ['!default', '!global'])) { + while ($lastNode[0] === Type::T_KEYWORD && \in_array($lastNode[1], ['!default', '!global'])) { array_pop($token[2]); - $node = end($token[2]); - - $token = $this->flattenList($token); - - $flags[] = $lastNode[1]; - + $node = end($token[2]); + $token = $this->flattenList($token); + $flags[] = $lastNode[1]; $lastNode = $node; } } @@ -2906,12 +3287,11 @@ protected function stripAssignmentFlags(&$value) protected function stripOptionalFlag(&$selectors) { $optional = false; - $selector = end($selectors); - $part = end($selector); + $part = end($selector); if ($part === ['!optional']) { - array_pop($selectors[count($selectors) - 1]); + array_pop($selectors[\count($selectors) - 1]); $optional = true; } @@ -2928,55 +3308,13 @@ protected function stripOptionalFlag(&$selectors) */ protected function flattenList($value) { - if ($value[0] === Type::T_LIST && count($value[2]) === 1) { + if ($value[0] === Type::T_LIST && \count($value[2]) === 1) { return $this->flattenList($value[2][0]); } return $value; } - /** - * @deprecated - * - * {@internal - * advance counter to next occurrence of $what - * $until - don't include $what in advance - * $allowNewline, if string, will be used as valid char set - * }} - */ - protected function to($what, &$out, $until = false, $allowNewline = false) - { - if (is_string($allowNewline)) { - $validChars = $allowNewline; - } else { - $validChars = $allowNewline ? '.' : "[^\n]"; - } - - if (! $this->match('(' . $validChars . '*?)' . $this->pregQuote($what), $m, ! $until)) { - return false; - } - - if ($until) { - $this->count -= strlen($what); // give back $what - } - - $out = $m[1]; - - return true; - } - - /** - * @deprecated - */ - protected function show() - { - if ($this->peek("(.*?)(\n|$)", $m, $this->count)) { - return $m[1]; - } - - return ''; - } - /** * Quote regular expression * @@ -3004,10 +3342,10 @@ private function extractLineNumbers($buffer) $prev = $pos + 1; } - $this->sourcePositions[] = strlen($buffer); + $this->sourcePositions[] = \strlen($buffer); if (substr($buffer, -1) !== "\n") { - $this->sourcePositions[] = strlen($buffer) + 1; + $this->sourcePositions[] = \strlen($buffer) + 1; } } @@ -3021,7 +3359,7 @@ private function extractLineNumbers($buffer) private function getSourcePosition($pos) { $low = 0; - $high = count($this->sourcePositions); + $high = \count($this->sourcePositions); while ($low < $high) { $mid = (int) (($high + $low) / 2); @@ -3047,13 +3385,7 @@ private function getSourcePosition($pos) */ private function saveEncoding() { - if (version_compare(PHP_VERSION, '7.2.0') >= 0) { - return; - } - - $iniDirective = 'mbstring' . '.func_overload'; // deprecated in PHP 7.2 - - if (ini_get($iniDirective) & 2) { + if (\extension_loaded('mbstring')) { $this->encoding = mb_internal_encoding(); mb_internal_encoding('iso-8859-1'); @@ -3065,7 +3397,7 @@ private function saveEncoding() */ private function restoreEncoding() { - if ($this->encoding) { + if (\extension_loaded('mbstring') && $this->encoding) { mb_internal_encoding($this->encoding); } } diff --git a/scssphp/scssphp/src/SourceMap/Base64.php b/scssphp/scssphp/src/SourceMap/Base64.php index 93c6c1b47..ed2e1fc54 100644 --- a/scssphp/scssphp/src/SourceMap/Base64.php +++ b/scssphp/scssphp/src/SourceMap/Base64.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/SourceMap/Base64VLQ.php b/scssphp/scssphp/src/SourceMap/Base64VLQ.php index d6f6452b5..86e57847c 100644 --- a/scssphp/scssphp/src/SourceMap/Base64VLQ.php +++ b/scssphp/scssphp/src/SourceMap/Base64VLQ.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -61,7 +61,9 @@ public static function encode($value) do { $digit = $vlq & self::VLQ_BASE_MASK; - $vlq >>= self::VLQ_BASE_SHIFT; + + //$vlq >>>= self::VLQ_BASE_SHIFT; // unsigned right shift + $vlq = (($vlq >> 1) & PHP_INT_MAX) >> (self::VLQ_BASE_SHIFT - 1); if ($vlq > 0) { $digit |= self::VLQ_CONTINUATION_BIT; @@ -130,8 +132,19 @@ private static function toVLQSigned($value) private static function fromVLQSigned($value) { $negate = ($value & 1) === 1; - $value = $value >> 1; - return $negate ? -$value : $value; + //$value >>>= 1; // unsigned right shift + $value = ($value >> 1) & PHP_INT_MAX; + + if (! $negate) { + return $value; + } + + // We need to OR 0x80000000 here to ensure the 32nd bit (the sign bit) is + // always set for negative numbers. If `value` were 1, (meaning `negate` is + // true and all other bits were zeros), `value` would now be 0. -0 is just + // 0, and doesn't flip the 32nd bit as intended. All positive numbers will + // successfully flip the 32nd bit without issue, so it's a noop for them. + return -$value | 0x80000000; } } diff --git a/scssphp/scssphp/src/SourceMap/Base64VLQEncoder.php b/scssphp/scssphp/src/SourceMap/Base64VLQEncoder.php deleted file mode 100644 index 365b4d930..000000000 --- a/scssphp/scssphp/src/SourceMap/Base64VLQEncoder.php +++ /dev/null @@ -1,217 +0,0 @@ - - * @author Nicolas FRANÇOIS - */ -class Base64VLQEncoder -{ - /** - * Shift - * - * @var integer - */ - private $shift = 5; - - /** - * Mask - * - * @var integer - */ - private $mask = 0x1F; // == (1 << shift) == 0b00011111 - - /** - * Continuation bit - * - * @var integer - */ - private $continuationBit = 0x20; // == (mask - 1 ) == 0b00100000 - - /** - * Char to integer map - * - * @var array - */ - private $charToIntMap = [ - 'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7, - 'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13, 'O' => 14, 'P' => 15, - 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20, 'V' => 21, 'W' => 22, 'X' => 23, - 'Y' => 24, 'Z' => 25, 'a' => 26, 'b' => 27, 'c' => 28, 'd' => 29, 'e' => 30, 'f' => 31, - 'g' => 32, 'h' => 33, 'i' => 34, 'j' => 35, 'k' => 36, 'l' => 37, 'm' => 38, 'n' => 39, - 'o' => 40, 'p' => 41, 'q' => 42, 'r' => 43, 's' => 44, 't' => 45, 'u' => 46, 'v' => 47, - 'w' => 48, 'x' => 49, 'y' => 50, 'z' => 51, 0 => 52, 1 => 53, 2 => 54, 3 => 55, - 4 => 56, 5 => 57, 6 => 58, 7 => 59, 8 => 60, 9 => 61, '+' => 62, '/' => 63, - ]; - - /** - * Integer to char map - * - * @var array - */ - private $intToCharMap = [ - 0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G', 7 => 'H', - 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N', 14 => 'O', 15 => 'P', - 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U', 21 => 'V', 22 => 'W', 23 => 'X', - 24 => 'Y', 25 => 'Z', 26 => 'a', 27 => 'b', 28 => 'c', 29 => 'd', 30 => 'e', 31 => 'f', - 32 => 'g', 33 => 'h', 34 => 'i', 35 => 'j', 36 => 'k', 37 => 'l', 38 => 'm', 39 => 'n', - 40 => 'o', 41 => 'p', 42 => 'q', 43 => 'r', 44 => 's', 45 => 't', 46 => 'u', 47 => 'v', - 48 => 'w', 49 => 'x', 50 => 'y', 51 => 'z', 52 => '0', 53 => '1', 54 => '2', 55 => '3', - 56 => '4', 57 => '5', 58 => '6', 59 => '7', 60 => '8', 61 => '9', 62 => '+', 63 => '/', - ]; - - /** - * Constructor - */ - public function __construct() - { - // I leave it here for future reference - // foreach (str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') as $i => $char) - // { - // $this->charToIntMap[$char] = $i; - // $this->intToCharMap[$i] = $char; - // } - } - - /** - * Convert from a two-complement value to a value where the sign bit is - * is placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - * We generate the value for 32 bit machines, hence -2147483648 becomes 1, not 4294967297, - * even on a 64 bit machine. - * - * @param string $aValue - */ - public function toVLQSigned($aValue) - { - return 0xffffffff & ($aValue < 0 ? ((-$aValue) << 1) + 1 : ($aValue << 1) + 0); - } - - /** - * Convert to a two-complement value from a value where the sign bit is - * is placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - * We assume that the value was generated with a 32 bit machine in mind. - * Hence - * 1 becomes -2147483648 - * even on a 64 bit machine. - * - * @param integer $aValue - */ - public function fromVLQSigned($aValue) - { - return $aValue & 1 ? $this->zeroFill(~$aValue + 2, 1) | (-1 - 0x7fffffff) : $this->zeroFill($aValue, 1); - } - - /** - * Return the base 64 VLQ encoded value. - * - * @param string $aValue The value to encode - * - * @return string The encoded value - */ - public function encode($aValue) - { - $encoded = ''; - $vlq = $this->toVLQSigned($aValue); - - do { - $digit = $vlq & $this->mask; - $vlq = $this->zeroFill($vlq, $this->shift); - - if ($vlq > 0) { - $digit |= $this->continuationBit; - } - - $encoded .= $this->base64Encode($digit); - } while ($vlq > 0); - - return $encoded; - } - - /** - * Return the value decoded from base 64 VLQ. - * - * @param string $encoded The encoded value to decode - * - * @return integer The decoded value - */ - public function decode($encoded) - { - $vlq = 0; - $i = 0; - - do { - $digit = $this->base64Decode($encoded[$i]); - $vlq |= ($digit & $this->mask) << ($i * $this->shift); - $i++; - } while ($digit & $this->continuationBit); - - return $this->fromVLQSigned($vlq); - } - - /** - * Right shift with zero fill. - * - * @param integer $a number to shift - * @param integer $b number of bits to shift - * - * @return integer - */ - public function zeroFill($a, $b) - { - return ($a >= 0) ? ($a >> $b) : ($a >> $b) & (PHP_INT_MAX >> ($b - 1)); - } - - /** - * Encode single 6-bit digit as base64. - * - * @param integer $number - * - * @return string - * - * @throws \Exception If the number is invalid - */ - public function base64Encode($number) - { - if ($number < 0 || $number > 63) { - throw new \Exception(sprintf('Invalid number "%s" given. Must be between 0 and 63.', $number)); - } - - return $this->intToCharMap[$number]; - } - - /** - * Decode single 6-bit digit from base64 - * - * @param string $char - * - * @return integer - * - * @throws \Exception If the number is invalid - */ - public function base64Decode($char) - { - if (! array_key_exists($char, $this->charToIntMap)) { - throw new \Exception(sprintf('Invalid base 64 digit "%s" given.', $char)); - } - - return $this->charToIntMap[$char]; - } -} diff --git a/scssphp/scssphp/src/SourceMap/SourceMapGenerator.php b/scssphp/scssphp/src/SourceMap/SourceMapGenerator.php index d0231b49d..1743326a8 100644 --- a/scssphp/scssphp/src/SourceMap/SourceMapGenerator.php +++ b/scssphp/scssphp/src/SourceMap/SourceMapGenerator.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -132,7 +132,7 @@ public function addMapping($generatedLine, $generatedColumn, $originalLine, $ori public function saveMap($content) { $file = $this->options['sourceMapWriteTo']; - $dir = dirname($file); + $dir = \dirname($file); // directory does not exist if (! is_dir($dir)) { @@ -201,7 +201,7 @@ public function generateJson() } // less.js compat fixes - if (count($sourceMap['sources']) && empty($sourceMap['sourceRoot'])) { + if (\count($sourceMap['sources']) && empty($sourceMap['sourceRoot'])) { unset($sourceMap['sourceRoot']); } @@ -235,7 +235,7 @@ protected function getSourcesContent() */ public function generateMappings() { - if (! count($this->mappings)) { + if (! \count($this->mappings)) { return ''; } @@ -249,6 +249,7 @@ public function generateMappings() } ksort($groupedMap); + $lastGeneratedLine = $lastOriginalIndex = $lastOriginalLine = $lastOriginalColumn = 0; foreach ($groupedMap as $lineNumber => $lineMap) { @@ -313,8 +314,8 @@ protected function normalizeFilename($filename) $basePath = $this->options['sourceMapBasepath']; // "Trim" the 'sourceMapBasepath' from the output filename. - if (strlen($basePath) && strpos($filename, $basePath) === 0) { - $filename = substr($filename, strlen($basePath)); + if (\strlen($basePath) && strpos($filename, $basePath) === 0) { + $filename = substr($filename, \strlen($basePath)); } // Remove extra leading path separators. diff --git a/scssphp/scssphp/src/Type.php b/scssphp/scssphp/src/Type.php index a12da72f2..c96a91786 100644 --- a/scssphp/scssphp/src/Type.php +++ b/scssphp/scssphp/src/Type.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -27,6 +27,7 @@ class Type const T_COMMENT = 'comment'; const T_CONTINUE = 'continue'; const T_CONTROL = 'control'; + const T_CUSTOM_PROPERTY = 'custom'; const T_DEBUG = 'debug'; const T_DIRECTIVE = 'directive'; const T_EACH = 'each'; diff --git a/scssphp/scssphp/src/Util.php b/scssphp/scssphp/src/Util.php index b0b76fdb4..a5c25aaff 100644 --- a/scssphp/scssphp/src/Util.php +++ b/scssphp/scssphp/src/Util.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * diff --git a/scssphp/scssphp/src/Version.php b/scssphp/scssphp/src/Version.php index cc616c0fe..2b38067e1 100644 --- a/scssphp/scssphp/src/Version.php +++ b/scssphp/scssphp/src/Version.php @@ -2,7 +2,7 @@ /** * SCSSPHP * - * @copyright 2012-2019 Leaf Corcoran + * @copyright 2012-2020 Leaf Corcoran * * @license http://opensource.org/licenses/MIT MIT * @@ -18,5 +18,5 @@ */ class Version { - const VERSION = 'v1.0.3'; + const VERSION = '1.1.1'; }