From cc887c29fd0e1d91e9c1027ac02abe4b3c79ecf8 Mon Sep 17 00:00:00 2001 From: Molkobain Date: Tue, 14 Jan 2020 09:48:43 +0100 Subject: [PATCH] =?UTF-8?q?N=C2=B02696=20-=20Upgrade=20SCSSPHP=20to=20v1.0?= =?UTF-8?q?.6=20(PHP=207.4=20compatibility)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 2 +- composer.lock | 18 +- lib/bin/pscss | 10 +- lib/composer/autoload_classmap.php | 1 - lib/composer/autoload_static.php | 1 - lib/composer/installed.json | 18 +- lib/scssphp/scssphp/README.md | 2 +- lib/scssphp/scssphp/bin/pscss | 32 +- lib/scssphp/scssphp/composer.json | 9 +- lib/scssphp/scssphp/src/Cache.php | 30 +- lib/scssphp/scssphp/src/Colors.php | 69 +- lib/scssphp/scssphp/src/Compiler.php | 1951 ++++++++++++----- lib/scssphp/scssphp/src/Formatter.php | 85 +- .../scssphp/src/Formatter/Expanded.php | 2 +- lib/scssphp/scssphp/src/Formatter/Nested.php | 191 +- lib/scssphp/scssphp/src/Node/Number.php | 12 +- lib/scssphp/scssphp/src/Parser.php | 597 +++-- .../scssphp/src/SourceMap/Base64VLQ.php | 13 +- .../src/SourceMap/Base64VLQEncoder.php | 217 -- lib/scssphp/scssphp/src/Version.php | 2 +- 20 files changed, 2233 insertions(+), 1029 deletions(-) delete mode 100644 lib/scssphp/scssphp/src/SourceMap/Base64VLQEncoder.php diff --git a/composer.json b/composer.json index 38d6a93a8..26c6c8686 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "nikic/php-parser": "^3.1", "pear/archive_tar": "1.4.7", "pelago/emogrifier": "2.1.0", - "scssphp/scssphp": "1.0.0", + "scssphp/scssphp": "1.0.6", "swiftmailer/swiftmailer": "5.4.12", "symfony/console": "3.4.*", "symfony/dotenv": "3.4.*", diff --git a/composer.lock b/composer.lock index 38bd72bb7..39a9594be 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": "fad30bc7d8ddf9c9cb9c70ab7c3ce385", + "content-hash": "fa67ef7539c664354f726be04d0d044c", "packages": [ { "name": "combodo/tcpdf", @@ -639,23 +639,25 @@ }, { "name": "scssphp/scssphp", - "version": "1.0.0", + "version": "1.0.6", "source": { "type": "git", "url": "https://github.com/scssphp/scssphp.git", - "reference": "6c8734b6edcf6c2fa785ad874b998fa854a7d030" + "reference": "5b3c9d704950d8f9637f5110c36c281ec47dc13c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/scssphp/scssphp/zipball/6c8734b6edcf6c2fa785ad874b998fa854a7d030", - "reference": "6c8734b6edcf6c2fa785ad874b998fa854a7d030", + "url": "https://api.github.com/repos/scssphp/scssphp/zipball/5b3c9d704950d8f9637f5110c36c281ec47dc13c", + "reference": "5b3c9d704950d8f9637f5110c36c281ec47dc13c", "shasum": "" }, "require": { - "php": "^5.6.0 || ^7" + "ext-ctype": "*", + "ext-json": "*", + "php": ">=5.6.0" }, "require-dev": { - "phpunit/phpunit": "~4.6", + "phpunit/phpunit": "^5.7 || ^6.5 || ^7.5 || ^8.3", "squizlabs/php_codesniffer": "~2.5", "twbs/bootstrap": "~4.3", "zurb/foundation": "~6.5" @@ -694,7 +696,7 @@ "scss", "stylesheet" ], - "time": "2019-06-05T01:22:01+00:00" + "time": "2019-12-12T05:00:52+00:00" }, { "name": "swiftmailer/swiftmailer", diff --git a/lib/bin/pscss b/lib/bin/pscss index f51e85776..2879dcb97 100644 --- a/lib/bin/pscss +++ b/lib/bin/pscss @@ -2,9 +2,13 @@ dir=$(cd "${0%[/\\]*}" > /dev/null; cd "../scssphp/scssphp/bin" && pwd) -if [ -d /proc/cygdrive ] && [[ $(which php) == $(readlink -n /proc/cygdrive)/* ]]; then - # We are in Cgywin using Windows php, so the path must be translated - dir=$(cygpath -m "$dir"); +if [ -d /proc/cygdrive ]; then + case $(which php) in + $(readlink -n /proc/cygdrive)/*) + # We are in Cygwin using Windows php, so the path must be translated + dir=$(cygpath -m "$dir"); + ;; + esac fi "${dir}/pscss" "$@" diff --git a/lib/composer/autoload_classmap.php b/lib/composer/autoload_classmap.php index 72abb91b0..0b4f45369 100644 --- a/lib/composer/autoload_classmap.php +++ b/lib/composer/autoload_classmap.php @@ -656,7 +656,6 @@ return array( '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/lib/composer/autoload_static.php b/lib/composer/autoload_static.php index 44b851639..9b6a75236 100644 --- a/lib/composer/autoload_static.php +++ b/lib/composer/autoload_static.php @@ -886,7 +886,6 @@ class ComposerStaticInit0018331147de7601e7552f7da8e3bb8b '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/lib/composer/installed.json b/lib/composer/installed.json index b0d591ab4..d0a6a8b68 100644 --- a/lib/composer/installed.json +++ b/lib/composer/installed.json @@ -656,29 +656,31 @@ }, { "name": "scssphp/scssphp", - "version": "1.0.0", - "version_normalized": "1.0.0.0", + "version": "1.0.6", + "version_normalized": "1.0.6.0", "source": { "type": "git", "url": "https://github.com/scssphp/scssphp.git", - "reference": "6c8734b6edcf6c2fa785ad874b998fa854a7d030" + "reference": "5b3c9d704950d8f9637f5110c36c281ec47dc13c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/scssphp/scssphp/zipball/6c8734b6edcf6c2fa785ad874b998fa854a7d030", - "reference": "6c8734b6edcf6c2fa785ad874b998fa854a7d030", + "url": "https://api.github.com/repos/scssphp/scssphp/zipball/5b3c9d704950d8f9637f5110c36c281ec47dc13c", + "reference": "5b3c9d704950d8f9637f5110c36c281ec47dc13c", "shasum": "" }, "require": { - "php": "^5.6.0 || ^7" + "ext-ctype": "*", + "ext-json": "*", + "php": ">=5.6.0" }, "require-dev": { - "phpunit/phpunit": "~4.6", + "phpunit/phpunit": "^5.7 || ^6.5 || ^7.5 || ^8.3", "squizlabs/php_codesniffer": "~2.5", "twbs/bootstrap": "~4.3", "zurb/foundation": "~6.5" }, - "time": "2019-06-05T01:22:01+00:00", + "time": "2019-12-12T05:00:52+00:00", "bin": [ "bin/pscss" ], diff --git a/lib/scssphp/scssphp/README.md b/lib/scssphp/scssphp/README.md index d08b31b2a..f541e4888 100644 --- a/lib/scssphp/scssphp/README.md +++ b/lib/scssphp/scssphp/README.md @@ -2,7 +2,7 @@ ### [![Build](https://travis-ci.org/scssphp/scssphp.svg?branch=master)](http://travis-ci.org/scssphp/scssphp) -[![License](https://poser.pugx.org/scssphp/scssphp/license.svg)](https://packagist.org/packages/scssphp/scssphp) +[![License](https://poser.pugx.org/scssphp/scssphp/license)](https://packagist.org/packages/scssphp/scssphp) `scssphp` is a compiler for SCSS written in PHP. diff --git a/lib/scssphp/scssphp/bin/pscss b/lib/scssphp/scssphp/bin/pscss index 811f8cbe5..f944b6325 100644 --- a/lib/scssphp/scssphp/bin/pscss +++ b/lib/scssphp/scssphp/bin/pscss @@ -12,8 +12,8 @@ error_reporting(E_ALL); -if (version_compare(PHP_VERSION, '5.4') < 0) { - die('Requires PHP 5.4 or above'); +if (version_compare(PHP_VERSION, '5.6') < 0) { + die('Requires PHP 5.6 or above'); } include __DIR__ . '/../scss.inc.php'; @@ -62,7 +62,7 @@ function parseArgument(&$i, $options) { } for ($i = 1; $i < $argc; $i++) { - if ($argv[$i] === '-h' || $argv[$i] === '--help') { + if ($argv[$i] === '-?' || $argv[$i] === '-h' || $argv[$i] === '--help') { $exe = $argv[0]; $HELP = <<=5.6.0", + "ext-json": "*", + "ext-ctype": "*" }, "require-dev": { "squizlabs/php_codesniffer": "~2.5", - "phpunit/phpunit": "~4.6", + "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/lib/scssphp/scssphp/src/Cache.php b/lib/scssphp/scssphp/src/Cache.php index 331126404..422497f49 100644 --- a/lib/scssphp/scssphp/src/Cache.php +++ b/lib/scssphp/scssphp/src/Cache.php @@ -32,7 +32,7 @@ use Exception; */ class Cache { - const CACHE_VERSION = 0; + const CACHE_VERSION = 1; // directory used for storing data public static $cacheDir = false; @@ -41,12 +41,12 @@ class Cache public static $prefix = 'scssphp_'; // force a refresh : 'once' for refreshing the first hit on a cache only, true to never use the cache in this hit - public static $forceFefresh = false; + public static $forceRefresh = false; // specifies the number of seconds after which data cached will be seen as 'garbage' and potentially cleaned up public static $gcLifetime = 604800; - // array of already refreshed cache if $forceFefresh==='once' + // array of already refreshed cache if $forceRefresh==='once' protected static $refreshed = []; /** @@ -57,12 +57,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 +74,7 @@ class Cache } if (isset($options['forceRefresh'])) { - self::$forceFefresh = $options['force_refresh']; + self::$forceRefresh = $options['forceRefresh']; } self::checkCacheDir(); @@ -97,13 +97,13 @@ class Cache { $fileCache = self::$cacheDir . self::cacheName($operation, $what, $options); - if ((! self::$forceRefresh || (self::$forceRefresh === 'once' && isset(self::$refreshed[$fileCache]))) - && file_exists($fileCache) + if (((self::$forceRefresh === false) || (self::$forceRefresh === 'once' && + isset(self::$refreshed[$fileCache]))) && file_exists($fileCache) ) { $cacheTime = filemtime($fileCache); - if ((is_null($lastModified) || $cacheTime > $lastModified) - && $cacheTime + self::$gcLifetime > time() + if ((is_null($lastModified) || $cacheTime > $lastModified) && + $cacheTime + self::$gcLifetime > time() ) { $c = file_get_contents($fileCache); $c = unserialize($c); @@ -176,13 +176,13 @@ class Cache 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/lib/scssphp/scssphp/src/Colors.php b/lib/scssphp/scssphp/src/Colors.php index ad459246a..ef6409aca 100644 --- a/lib/scssphp/scssphp/src/Colors.php +++ b/lib/scssphp/scssphp/src/Colors.php @@ -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,71 @@ 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) { + # specific case we dont' revert according to spec + #if (! $a && ! $r && ! $g && ! $b) { + # return 'transparent'; + #} + + 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/lib/scssphp/scssphp/src/Compiler.php b/lib/scssphp/scssphp/src/Compiler.php index 3446aeab9..711d3382f 100644 --- a/lib/scssphp/scssphp/src/Compiler.php +++ b/lib/scssphp/scssphp/src/Compiler.php @@ -164,6 +164,8 @@ class Compiler /** * Constructor + * + * @param array|null $cacheOptions */ public function __construct($cacheOptions = null) { @@ -173,8 +175,15 @@ class Compiler if ($cacheOptions) { $this->cache = new Cache($cacheOptions); } + + $this->stderr = fopen('php://stderr', 'w'); } + /** + * Get compiler options + * + * @return array + */ public function getCompileOptions() { $options = [ @@ -190,6 +199,16 @@ class Compiler return $options; } + /** + * Set an alternative error output stream, for testing purpose only + * + * @param resource $handle + */ + public function setErrorOuput($handle) + { + $this->stderr = $handle; + } + /** * Compile scss * @@ -203,19 +222,14 @@ class Compiler public function compile($code, $path = null) { if ($this->cache) { - $cacheKey = ($path ? $path : "(stdin)") . ":" . md5($code); + $cacheKey = ($path ? $path : "(stdin)") . ":" . md5($code); $compileOptions = $this->getCompileOptions(); - $cache = $this->cache->getCache("compile", $cacheKey, $compileOptions); + $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; } @@ -239,10 +253,9 @@ class Compiler $this->storeEnv = null; $this->charsetSeen = null; $this->shouldEvaluate = null; - $this->stderr = fopen('php://stderr', 'w'); $this->parser = $this->parserFactory($path); - $tree = $this->parser->parse($code); + $tree = $this->parser->parse($code); $this->parser = null; $this->formatter = new $this->formatter(); @@ -334,9 +347,9 @@ class Compiler /** * 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) { @@ -367,12 +380,12 @@ class Compiler 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; @@ -503,9 +516,12 @@ class Compiler } 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 ) { + while (count($new)>1 && substr($new[count($new) - 1], -1) !== '(') { + $part = array_pop($new) . $part; + } $new[count($new) - 1] .= $part; } else { $new[] = $part; @@ -527,9 +543,13 @@ class Compiler protected function matchExtends($selector, &$out, $from = 0, $initial = true) { static $partsPile = []; - $selector = $this->glueFunctionSelectors($selector); + if (count($selector) == 1 && in_array(reset($selector), $partsPile)) { + return; + } + + $outRecurs = []; foreach ($selector as $i => $part) { if ($i < $from) { continue; @@ -545,11 +565,10 @@ class Compiler } } - if ($this->matchExtendsSingle($part, $origin)) { - $partsPile[] = $part; + $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) { @@ -561,6 +580,9 @@ class Compiler $k++; } } + if (count($nonBreakableBefore) and $k == count($new)) { + $k--; + } $replacement = []; $tempReplacement = $k > 0 ? array_slice($new, $k) : $new; @@ -597,36 +619,93 @@ class Compiler 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); + 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; - 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); + } + } - array_pop($partsPile); + /** + * Test a part for being a pseudo selector + * @param string $part + * @param array $matches + * @return bool + */ + 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); + 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; } /** @@ -634,10 +713,11 @@ class Compiler * * @param array $rawSingle * @param array $outOrigin + * @param bool $initial * * @return boolean */ - protected function matchExtendsSingle($rawSingle, &$outOrigin) + protected function matchExtendsSingle($rawSingle, &$outOrigin, $initial = true) { $counts = []; $single = []; @@ -667,17 +747,41 @@ class Compiler $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; } } + 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; + } + } + } + } } - $outOrigin = []; - $found = false; - foreach ($counts as $idx => $count) { list($target, $origin, /* $block */) = $this->extends[$idx]; @@ -739,12 +843,13 @@ class Compiler { $parents = []; $children = []; + $j = $i = count($fragment); for (;;) { $children = $j != $i ? array_slice($fragment, $j, $i - $j) : []; - $parents = array_slice($fragment, 0, $j); - $slice = end($parents); + $parents = array_slice($fragment, 0, $j); + $slice = end($parents); if (empty($slice) || ! $this->isImmediateRelationshipCombinator($slice[0])) { break; @@ -766,22 +871,25 @@ class Compiler */ protected function combineSelectorSingle($base, $other) { - $tag = []; - $out = []; - $wasTag = true; + $tag = []; + $out = []; + $wasTag = false; - foreach ([$base, $other] as $single) { + foreach ([array_reverse($base), array_reverse($other)] as $single) { foreach ($single as $part) { - if (preg_match('/^[\[.:#]/', $part)) { + if (preg_match('/^[\[:]/', $part)) { $out[] = $part; $wasTag = false; + } elseif (preg_match('/^[\.#]/', $part)) { + array_unshift($out, $part); + $wasTag = false; } elseif (preg_match('/^[^_-]/', $part)) { $tag[] = $part; $wasTag = true; } elseif ($wasTag) { $tag[count($tag) - 1] .= $part; } else { - $out[count($out) - 1] .= $part; + $out[] = $part; } } } @@ -833,16 +941,17 @@ class Compiler 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; @@ -899,20 +1008,29 @@ class Compiler /** * 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 (! empty($block->value)) { - $s .= ' ' . $this->compileValue($block->value); - } - - if ($block->name === 'keyframes' || substr($block->name, -10) === '-keyframes') { - $this->compileKeyframeBlock($block, [$s]); + if (is_array($directive)) { + $s = '@' . $directive[0]; + if (! empty($directive[1])) { + $s .= ' ' . $this->compileValue($directive[1]); + } + $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]); + } } } @@ -925,7 +1043,7 @@ class Compiler { $env = $this->pushEnv($block); $envs = $this->compactEnv($env); - $without = isset($block->with) ? $this->compileWith($block->with) : static::WITH_RULE; + list($with, $without) = $this->compileWith(isset($block->with) ? $block->with : null); // wrap inline selector if ($block->selector) { @@ -952,10 +1070,10 @@ class Compiler $selfParent = $block->parent; } - $this->env = $this->filterWithout($envs, $without); + $this->env = $this->filterWithWithout($envs, $with, $without); $saveScope = $this->scope; - $this->scope = $this->filterScopeWithout($saveScope, $without); + $this->scope = $this->filterScopeWithWithout($saveScope, $with, $without); // propagate selfParent to the children where they still can be useful $this->compileChildrenNoReturn($block->children, $this->scope, $selfParent); @@ -971,13 +1089,15 @@ class Compiler * Filter at-root scope depending of with/without option * * @param \ScssPhp\ScssPhp\Formatter\OutputBlock $scope - * @param mixed $without + * @param array $with + * @param array $without * * @return mixed */ - protected function filterScopeWithout($scope, $without) + protected function filterScopeWithWithout($scope, $with, $without) { $filteredScopes = []; + $childStash = []; if ($scope->type === TYPE::T_ROOT) { return $scope; @@ -985,6 +1105,7 @@ class Compiler // start from the root while ($scope->parent && $scope->parent->type !== TYPE::T_ROOT) { + array_unshift($childStash, $scope); $scope = $scope->parent; } @@ -993,11 +1114,11 @@ class Compiler break; } - if (! $this->isWithout($without, $scope)) { + 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 = []; @@ -1006,7 +1127,9 @@ class Compiler $filteredScopes[] = $s; } - if ($scope->children) { + if (count($childStash)) { + $scope = array_shift($childStash); + } elseif ($scope->children) { $scope = end($scope->children); } else { $scope = null; @@ -1027,8 +1150,9 @@ class Compiler while (count($filteredScopes)) { $s = array_shift($filteredScopes); $s->parent = $p; - $p->children[] = &$s; - $p = $s; + $p->children[] = $s; + $newScope = &$p->children[0]; + $p = &$p->children[0]; } return $newScope; @@ -1084,72 +1208,64 @@ class Compiler } /** - * Compile @at-root's with: inclusion / without: exclusion into filter flags + * Compile @at-root's with: inclusion / without: exclusion into 2 lists uses to filter scope/env later * - * @param array $with + * @param array $withCondition * - * @return integer + * @return array */ - protected function compileWith($with) + protected function compileWith($withCondition) { - static $mapping = [ - 'rule' => self::WITH_RULE, - 'media' => self::WITH_MEDIA, - 'supports' => self::WITH_SUPPORTS, - 'all' => self::WITH_ALL, - ]; + // just compile what we have in 2 lists + $with = []; + $without = ['rule' => true]; - // exclude selectors by default - $without = static::WITH_RULE; + if ($withCondition) { + if ($this->libMapHasKey([$withCondition, static::$with])) { + $without = []; // cancel the default + $list = $this->coerceList($this->libMapGet([$withCondition, static::$with])); - if ($this->libMapHasKey([$with, static::$with])) { - $without = static::WITH_ALL; + foreach ($list[2] as $item) { + $keyword = $this->compileStringContent($this->coerceString($item)); - $list = $this->coerceList($this->libMapGet([$with, static::$with])); + $with[$keyword] = true; + } + } - foreach ($list[2] as $item) { - $keyword = $this->compileStringContent($this->coerceString($item)); + if ($this->libMapHasKey([$withCondition, static::$without])) { + $without = []; // cancel the default + $list = $this->coerceList($this->libMapGet([$withCondition, static::$without])); - if (array_key_exists($keyword, $mapping)) { - $without &= ~($mapping[$keyword]); + foreach ($list[2] as $item) { + $keyword = $this->compileStringContent($this->coerceString($item)); + + $without[$keyword] = true; } } } - if ($this->libMapHasKey([$with, static::$without])) { - $without = 0; - - $list = $this->coerceList($this->libMapGet([$with, static::$without])); - - foreach ($list[2] as $item) { - $keyword = $this->compileStringContent($this->coerceString($item)); - - if (array_key_exists($keyword, $mapping)) { - $without |= $mapping[$keyword]; - } - } - } - - return $without; + return [$with, $without]; } /** * Filter env stack * * @param array $envs - * @param integer $without + * @param array $with + * @param array $without * * @return \ScssPhp\ScssPhp\Compiler\Environment */ - protected function filterWithout($envs, $without) + protected function filterWithWithout($envs, $with, $without) { $filtered = []; foreach ($envs as $e) { - if ($e->block && $this->isWithout($without, $e->block)) { + 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; @@ -1162,36 +1278,71 @@ class Compiler /** * Filter WITH rules * - * @param integer $without * @param \ScssPhp\ScssPhp\Block|\ScssPhp\ScssPhp\Formatter\OutputBlock $block + * @param array $with + * @param array $without * * @return boolean */ - protected function isWithout($without, $block) + protected function isWith($block, $with, $without) { if (isset($block->type)) { if ($block->type === Type::T_MEDIA) { - return ($without & static::WITH_MEDIA) ? true : false; + return $this->testWithWithout('media', $with, $without); } if ($block->type === Type::T_DIRECTIVE) { - if (isset($block->name) && $block->name === 'supports') { - return ($without & static::WITH_SUPPORTS) ? true : false; - } - - if (isset($block->selectors) && strpos(serialize($block->selectors), '@supports') !== false) { - return ($without & static::WITH_SUPPORTS) ? true : false; + if (isset($block->name)) { + return $this->testWithWithout($block->name, $with, $without); + } elseif (isset($block->selectors) && preg_match(',@(\w+),ims', json_encode($block->selectors), $m)) { + return $this->testWithWithout($m[1], $with, $without); + } else { + return $this->testWithWithout('???', $with, $without); } } + } elseif (isset($block->selectors)) { + // a selector starting with number is a keyframe rule + if (count($block->selectors)) { + $s = reset($block->selectors); + + while (is_array($s)) { + $s = reset($s); + } + + if (is_object($s) && $s instanceof Node\Number) { + return $this->testWithWithout('keyframes', $with, $without); + } + } + + return $this->testWithWithout('rule', $with, $without); } - if ((($without & static::WITH_RULE) && isset($block->selectors))) { - return true; - } - - return false; + return true; } + /** + * Test a single type of block against with/without lists + * + * @param string $what + * @param array $with + * @param array $without + * + * @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)) { + return (isset($without[$what]) || isset($without['all'])) ? false : true; + } + + // otherwise reject all what is not in the with list + return (isset($with[$what]) || isset($with['all'])) ? true : false; + } + + /** * Compile keyframe block * @@ -1220,6 +1371,40 @@ class Compiler $this->popEnv(); } + /** + * Compile nested properties lines + * + * @param \ScssPhp\ScssPhp\Block $block + * @param OutputBlock $out + */ + protected function compileNestedPropertiesBlock(Block $block, OutputBlock $out) + { + $prefix = $this->compileValue($block->prefix) . '-'; + + $nested = $this->makeOutputBlock($block->type); + $nested->parent = $out; + + if ($block->hasValue) { + $nested->depth = $out->depth + 1; + } + + $out->children[] = $nested; + + foreach ($block->children as $child) { + switch ($child[0]) { + case Type::T_ASSIGN: + array_unshift($child[1][2], $prefix); + break; + + case Type::T_NESTED_PROPERTY: + array_unshift($child[1]->prefix[2], $prefix); + break; + } + + $this->compileChild($child, $nested); + } + } + /** * Compile nested block * @@ -1248,15 +1433,15 @@ class Compiler 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]]; } @@ -1333,17 +1518,50 @@ class Compiler $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(); + $storeEnv = $this->storeEnv; + $this->storeEnv = $this->env; + } + + try { + $c = $this->compileValue($value[2]); + } catch (\Exception $e) { + // ignore error in comment compilation which are only interpolation + } + + if ($pushEnv) { + $this->storeEnv = $storeEnv; + $this->popEnv(); + } + } + + return $c; + } + /** * Compile root level comment * @@ -1352,7 +1570,7 @@ class Compiler 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; } @@ -1373,8 +1591,8 @@ class Compiler // 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); @@ -1458,6 +1676,7 @@ class Compiler } else { $output[] = $compound; } + $glueNext = true; } elseif ($glueNext) { $output[count($output) - 1] .= ' ' . $compound; @@ -1471,6 +1690,7 @@ class Compiler foreach ($output as &$o) { $o = [Type::T_STRING, '', [$o]]; } + $output = [Type::T_LIST, ' ', $output]; } else { $output = implode(' ', $output); @@ -1628,6 +1848,7 @@ class Compiler // not displayed but you can var_dump it to deep debug $msg = $this->callStackMessage(true, 100); $msg = "Infinite calling loop"; + $this->throwError($msg); } } @@ -1682,7 +1903,7 @@ class Compiler $stm[1]->selfParent = $selfParent; $ret = $this->compileChild($stm, $out); $stm[1]->selfParent = null; - } elseif ($selfParent && $stm[0] === TYPE::T_INCLUDE) { + } elseif ($selfParent && in_array($stm[0], [TYPE::T_INCLUDE, TYPE::T_EXTEND])) { $stm['selfParent'] = $selfParent; $ret = $this->compileChild($stm, $out); unset($stm['selfParent']); @@ -1710,52 +1931,60 @@ class Compiler */ 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++) { $value = $this->compileValue($q[$i]); // the parser had no mean to know if media type or expression if it was an interpolation + // so you need to reparse if the T_MEDIA_TYPE looks like anything else a media type if ($q[0] == Type::T_MEDIA_TYPE && (strpos($value, '(') !== false || strpos($value, ')') !== false || - strpos($value, ':') !== false) + strpos($value, ':') !== false || + strpos($value, ',') !== false) ) { - $queryList[$kql][$kq][0] = Type::T_MEDIA_EXPRESSION; - - if (strpos($value, 'and') !== false) { - $values = explode('and', $value); - $value = trim(array_pop($values)); - - while ($v = trim(array_pop($values))) { - $type = Type::T_MEDIA_EXPRESSION; - - if (strpos($v, '(') === false && - strpos($v, ')') === false && - strpos($v, ':') === false - ) { - $type = Type::T_MEDIA_TYPE; - } - - if (substr($v, 0, 1) === '(' && substr($v, -1) === ')') { - $v = substr($v, 1, -1); - } - - $queryList[$kql][] = [$type,[Type::T_KEYWORD, $v]]; - } - } - - if (substr($value, 0, 1) === '(' && substr($value, -1) === ')') { - $value = substr($value, 1, -1); - } + $shouldReparse = true; } $queryList[$kql][$kq][$i] = [Type::T_KEYWORD, $value]; } } + + if ($shouldReparse) { + 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)) { + $outQueryList[] = array_shift($queries); + } + + continue; + } + } + } + + $outQueryList[] = $queryList[$kql]; } - return $queryList; + return $outQueryList; } /** @@ -1767,9 +1996,9 @@ class Compiler */ protected function compileMediaQuery($queryList) { - $start = '@media '; + $start = '@media '; $default = trim($start); - $out = []; + $out = []; $current = ""; foreach ($queryList as $query) { @@ -1789,6 +2018,7 @@ class Compiler switch ($q[0]) { case Type::T_MEDIA_TYPE: $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) )) { @@ -1809,8 +2039,8 @@ class Compiler } $current = ""; - $type = null; - $parts = []; + $type = null; + $parts = []; } } @@ -1942,23 +2172,19 @@ class Compiler return $type1; } - $m1 = ''; - $t1 = ''; - if (count($type1) > 1) { - $m1= strtolower($type1[0]); - $t1= strtolower($type1[1]); + $m1 = strtolower($type1[0]); + $t1 = strtolower($type1[1]); } else { + $m1 = ''; $t1 = strtolower($type1[0]); } - $m2 = ''; - $t2 = ''; - if (count($type2) > 1) { $m2 = strtolower($type2[0]); $t2 = strtolower($type2[1]); } else { + $m2 = ''; $t2 = strtolower($type2[0]); } @@ -2013,6 +2239,8 @@ class Compiler return true; } + $this->appendRootDirective('@import ' . $this->compileValue($rawPath). ';', $out); + return false; } @@ -2024,20 +2252,112 @@ class Compiler foreach ($rawPath[2] as $path) { if ($path[0] !== Type::T_STRING) { + $this->appendRootDirective('@import ' . $this->compileValue($rawPath) . ';', $out); + return false; } } foreach ($rawPath[2] as $path) { - $this->compileImport($path, $out); + $this->compileImport($path, $out, $once); } return true; } + $this->appendRootDirective('@import ' . $this->compileValue($rawPath) . ';', $out); + return false; } + + /** + * Append a root directive like @import or @charset as near as the possible from the source code + * (keeping before comments, @import and @charset coming before in the source code) + * + * @param string $line + * @param @param \ScssPhp\ScssPhp\Formatter\OutputBlock $out + * @param array $allowed + */ + protected function appendRootDirective($line, $out, $allowed = [Type::T_COMMENT]) + { + $root = $out; + + while ($root->parent) { + $root = $root->parent; + } + + $i = 0; + + while ($i < count($root->children)) { + if (! isset($root->children[$i]->type) || ! in_array($root->children[$i]->type, $allowed)) { + break; + } + + $i++; + } + + // remove incompatible children from the bottom of the list + $saveChildren = []; + + 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->sourceColumn = $this->sourceColumn; + + $root->children[] = $child; + + // repush children + while (count($saveChildren)) { + $root->children[] = array_pop($saveChildren); + } + } + + /** + * 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|mixed $line + */ + protected function appendOutputLine(OutputBlock $out, $type, $line) + { + $outWrite = &$out; + + if ($type === Type::T_COMMENT) { + $parent = $out->parent; + + if (end($parent->children) !== $out) { + $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 ($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; + + $out->children[] = $nextLines; + $outWrite = &$nextLines; + } + } + + $outWrite->lines[] = $line; + } + /** * Compile child; returns a value to halt execution * @@ -2049,16 +2369,17 @@ class Compiler 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; + $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; @@ -2069,21 +2390,17 @@ class Compiler case Type::T_SCSSPHP_IMPORT_ONCE: $rawPath = $this->reduce($child[1]); - if (! $this->compileImport($rawPath, $out, true)) { - $out->lines[] = '@import ' . $this->compileValue($rawPath) . ';'; - } + $this->compileImport($rawPath, $out, true); break; case Type::T_IMPORT: $rawPath = $this->reduce($child[1]); - if (! $this->compileImport($rawPath, $out)) { - $out->lines[] = '@import ' . $this->compileValue($rawPath) . ';'; - } + $this->compileImport($rawPath, $out); break; case Type::T_DIRECTIVE: - $this->compileDirective($child[1]); + $this->compileDirective($child[1], $out); break; case Type::T_AT_ROOT: @@ -2101,8 +2418,7 @@ class Compiler case Type::T_CHARSET: if (! $this->charsetSeen) { $this->charsetSeen = true; - - $out->lines[] = '@charset ' . $this->compileValue($child[1]) . ';'; + $this->appendRootDirective('@charset ' . $this->compileValue($child[1]) . ';', $out); } break; @@ -2110,9 +2426,9 @@ class Compiler list(, $name, $value) = $child; if ($name[0] === Type::T_VARIABLE) { - $flags = isset($child[3]) ? $child[3] : []; + $flags = isset($child[3]) ? $child[3] : []; $isDefault = in_array('!default', $flags); - $isGlobal = in_array('!global', $flags); + $isGlobal = in_array('!global', $flags); if ($isGlobal) { $this->set($name[1], $this->reduce($value), false, $this->rootEnv, $value); @@ -2120,8 +2436,8 @@ class Compiler } $shouldSet = $isDefault && - (($result = $this->get($name[1], false)) === null - || $result === static::$null); + (is_null($result = $this->get($name[1], false)) || + $result === static::$null); if (! $isDefault || $shouldSet) { $this->set($name[1], $this->reduce($value), true, null, $value); @@ -2131,28 +2447,77 @@ class Compiler $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; - if ($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]; + $shorthandDividerNeedsUnit = false; + $maxListElements = null; + $maxShorthandDividers = 1; + + switch ($compiledName) { + case 'border-radius': + $maxListElements = 4; + $shorthandDividerNeedsUnit = true; + break; } - if ($fontValue[0] === Type::T_EXPRESSION && $fontValue[1] === '/') { - $fontValue = $this->expToString($fontValue); - } elseif ($fontValue[0] === Type::T_LIST) { - foreach ($fontValue[2] as &$item) { + 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 + $shorthandValue=&$value[2][0]; + } + + 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--; + } + } } } } @@ -2170,10 +2535,11 @@ class Compiler $compiledValue = $this->compileValue($value); - $out->lines[] = $this->formatter->property( + $line = $this->formatter->property( $compiledName, $compiledValue ); + $this->appendOutputLine($out, Type::T_ASSIGN, $line); break; case Type::T_COMMENT: @@ -2182,14 +2548,16 @@ class Compiler break; } - $out->lines[] = $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; - - $this->set(static::$namespaces[$block->type] . $block->name, $block); + // 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; case Type::T_EXTEND: @@ -2199,8 +2567,13 @@ class Compiler foreach ($results as $result) { // only use the first one $result = current($result); + $selectors = $out->selectors; - $this->pushExtends($result, $out->selectors, $child); + if (! $selectors && isset($child['selfParent'])) { + $selectors = $this->multiplySelectors($this->env, $child['selfParent']); + } + + $this->pushExtends($result, $selectors, $child); } } break; @@ -2327,31 +2700,12 @@ class Compiler return $this->reduce($child[1], true); case Type::T_NESTED_PROPERTY: - list(, $prop) = $child; - - $prefixed = []; - $prefix = $this->compileValue($prop->prefix) . '-'; - - foreach ($prop->children as $child) { - switch ($child[0]) { - case Type::T_ASSIGN: - array_unshift($child[1][2], $prefix); - break; - - case Type::T_NESTED_PROPERTY: - array_unshift($child[1]->prefix[2], $prefix); - break; - } - - $prefixed[] = $child; - } - - $this->compileChildrenNoReturn($prefixed, $out); + $this->compileNestedPropertiesBlock($child[1], $out); break; case Type::T_INCLUDE: // including a mixin - list(, $name, $argValues, $content) = $child; + list(, $name, $argValues, $content, $argUsing) = $child; $mixin = $this->get(static::$namespaces['mixin'] . $name, false); @@ -2394,9 +2748,18 @@ class Compiler // i.e., recursive @include of the same mixin if (isset($content)) { $copyContent = clone $content; - $copyContent->scope = $callingScope; + $copyContent->scope = clone $callingScope; $this->setRaw(static::$namespaces['special'] . 'content', $copyContent, $this->env); + } else { + $this->setRaw(static::$namespaces['special'] . 'content', null, $this->env); + } + + // save the "using" argument list for applying it to when "@content" is invoked + if (isset($argUsing)) { + $this->setRaw(static::$namespaces['special'] . 'using', $argUsing, $this->env); + } else { + $this->setRaw(static::$namespaces['special'] . 'using', null, $this->env); } if (isset($mixin->args)) { @@ -2405,6 +2768,12 @@ class Compiler $this->env->marker = 'mixin'; + if (! empty($mixin->parentEnv)) { + $this->env->declarationScopeParent = $mixin->parentEnv; + } else { + $this->throwError("@mixin $name() without parentEnv"); + } + $this->compileChildrenNoReturn($mixin->children, $out, $selfParent, $this->env->marker . " " . $name); $this->storeEnv = $storeEnv; @@ -2413,18 +2782,35 @@ class Compiler break; case Type::T_MIXIN_CONTENT: - $env = isset($this->storeEnv) ? $this->storeEnv : $this->env; - $content = $this->get(static::$namespaces['special'] . 'content', 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 = $this->storeEnv->parent->block->children; + $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; + $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); + } + $this->compileChildrenNoReturn($content->children, $out); $this->storeEnv = $storeEnv; @@ -2434,8 +2820,9 @@ class Compiler 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; @@ -2443,8 +2830,9 @@ class Compiler 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; @@ -2452,8 +2840,9 @@ class Compiler 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; @@ -2548,10 +2937,13 @@ class Compiler * @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: @@ -2567,16 +2959,15 @@ class Compiler } // special case: looks like css shorthand - if ($opName == 'div' && ! $inParens && ! $inExp && isset($right[2]) - && (($right[0] !== Type::T_NUMBER && $right[2] != '') - || ($right[0] === Type::T_NUMBER && ! $right->unitless())) + if ($opName == 'div' && ! $inParens && ! $inExp && isset($right[2]) && + (($right[0] !== Type::T_NUMBER && $right[2] != '') || + ($right[0] === Type::T_NUMBER && ! $right->unitless())) ) { return $this->expToString($value); } - $left = $this->coerceForExpression($left); + $left = $this->coerceForExpression($left); $right = $this->coerceForExpression($right); - $ltype = $left[0]; $rtype = $right[0]; @@ -2717,6 +3108,7 @@ class Compiler case Type::T_INTERPOLATE: $value[1] = $this->reduce($value[1]); + if ($inExp) { return $value[1]; } @@ -2729,6 +3121,7 @@ class Compiler case Type::T_SELF: $selfSelector = $this->multiplySelectors($this->env); $selfSelector = $this->collapseSelectors($selfSelector, true); + return $selfSelector; default: @@ -2803,6 +3196,10 @@ class Compiler $value[2][$key] = $this->normalizeValue($item); } + if (! empty($value['enclosing'])) { + unset($value['enclosing']); + } + return $value; case Type::T_STRING: @@ -3219,7 +3616,7 @@ class Compiler * * @param array $value * - * @return string + * @return string|array */ public function compileValue($value) { @@ -3236,14 +3633,38 @@ class Compiler // [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 && $value[4] !== 1) { // rgba - $a = new Node\Number($value[4], ''); + if (count($value) === 5) { + $alpha = $this->compileRGBAValue($value[4], true); - return 'rgba(' . $r . ', ' . $g . ', ' . $b . ', ' . $a . ')'; + 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 . ')'; + } + + $colorName = Colors::RGBaToColorName($r, $g, $b); + + if (! is_null($colorName)) { + return $colorName; } $h = sprintf('#%02x%02x%02x', $r, $g, $b); @@ -3274,9 +3695,28 @@ class Compiler } 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 = []; @@ -3286,14 +3726,18 @@ class Compiler 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++) { @@ -3311,11 +3755,23 @@ class Compiler list(, $interpolate, $left, $right) = $value; list(,, $whiteLeft, $whiteRight) = $interpolate; + $delim = $left[1]; + + if ($delim && $delim !== ' ' && ! $whiteLeft) { + $delim .= ' '; + } + $left = count($left[2]) > 0 ? - $this->compileValue($left) . $whiteLeft : ''; + $this->compileValue($left) . $delim . $whiteLeft: ''; + + $delim = $right[1]; + + if ($delim && $delim !== ' ') { + $delim .= ' '; + } $right = count($right[2]) > 0 ? - $whiteRight . $this->compileValue($right) : ''; + $whiteRight . $delim . $this->compileValue($right) : ''; return $left . $this->compileValue($interpolate) . $right; @@ -3345,6 +3801,7 @@ class Compiler } $temp = $this->compileValue([Type::T_KEYWORD, $item]); + if ($temp[0] === Type::T_STRING) { $filtered[] = $this->compileStringContent($temp); } elseif ($temp[0] === Type::T_KEYWORD) { @@ -3370,8 +3827,11 @@ class Compiler case Type::T_NULL: return 'null'; + case Type::T_COMMENT: + return $this->compileCommentValue($value); + default: - $this->throwError("unknown value type: $value[0]"); + $this->throwError("unknown value type: ".json_encode($value)); } } @@ -3460,9 +3920,9 @@ class Compiler $selectors = $env->selectors; do { - $stillHasSelf = false; + $stillHasSelf = false; $prevSelectors = $selectors; - $selectors = []; + $selectors = []; foreach ($prevSelectors as $selector) { foreach ($parentSelectors as $parent) { @@ -3528,9 +3988,11 @@ class Compiler foreach ($parentPart as $pp) { if (is_array($pp)) { $flatten = []; + array_walk_recursive($pp, function ($a) use (&$flatten) { $flatten[] = $a; }); + $pp = implode($flatten); } @@ -3574,12 +4036,14 @@ class Compiler : [[[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; @@ -3771,7 +4235,6 @@ class Compiler $env = $this->getStoreEnv(); } - $nextIsRoot = false; $hasNamespace = $normalizedName[0] === '^' || $normalizedName[0] === '@' || $normalizedName[0] === '%'; $maxDepth = 10000; @@ -3790,12 +4253,16 @@ class Compiler } 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; } @@ -3807,7 +4274,7 @@ class Compiler } if ($shouldThrow) { - $this->throwError("Undefined variable \$$name" . ($maxDepth<=0 ? " (infinite recursion)" : "")); + $this->throwError("Undefined variable \$$name" . ($maxDepth <= 0 ? " (infinite recursion)" : "")); } // found nothing @@ -3824,7 +4291,7 @@ class Compiler */ protected function has($name, Environment $env = null) { - return $this->get($name, false, $env) !== null; + return ! is_null($this->get($name, false, $env)); } /** @@ -3898,7 +4365,7 @@ class Compiler */ public function addParsedFile($path) { - if (isset($path) && file_exists($path)) { + if (isset($path) && is_file($path)) { $this->parsedFiles[realpath($path)] = filemtime($path); } } @@ -4063,6 +4530,7 @@ class Compiler } $pi = pathinfo($path); + array_unshift($this->importPaths, $pi['dirname']); $this->compileChildrenNoReturn($tree->children, $out); array_shift($this->importPaths); @@ -4082,9 +4550,9 @@ class Compiler $urls = []; // for "normal" scss imports (ignore vanilla css and external requests) - if (! preg_match('/\.css$|^https?:\/\//', $url)) { + if (! preg_match('~\.css$|^https?://~', $url)) { // try both normal and the _partial filename - $urls = [$url, preg_replace('/[^\/]+$/', '_\0', $url)]; + $urls = [$url, preg_replace('~[^/]+$~', '_\0', $url)]; } $hasExtension = preg_match('/[.]s?css$/', $url); @@ -4100,8 +4568,8 @@ class Compiler ) ? '/' : ''; $full = $dir . $separator . $full; - if ($this->fileExists($file = $full . '.scss') || - ($hasExtension && $this->fileExists($file = $full)) + if (is_file($file = $full . '.scss') || + ($hasExtension && is_file($file = $full)) ) { return $file; } @@ -4110,7 +4578,7 @@ class Compiler // check custom callback for import path $file = call_user_func($dir, $url); - if ($file !== null) { + if (! is_null($file)) { return $file; } } @@ -4205,9 +4673,10 @@ class Compiler ? $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; } } @@ -4227,6 +4696,10 @@ class Compiler 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) { @@ -4236,18 +4709,6 @@ class Compiler } } - /** - * Does file exist? - * - * @param string $name - * - * @return boolean - */ - protected function fileExists($name) - { - return file_exists($name) && is_file($name); - } - /** * Call SCSS @function * @@ -4281,6 +4742,11 @@ class Compiler $tmp->children = []; $this->env->marker = 'function'; + if (! empty($func->parentEnv)) { + $this->env->declarationScopeParent = $func->parentEnv; + } else { + $this->throwError("@function $name() without parentEnv"); + } $ret = $this->compileChildren($func->children, $tmp, $this->env->marker . " " . $name); @@ -4317,11 +4783,17 @@ class Compiler return false; } - @list($sorted, $kwargs) = $this->sortArgs($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, true); + $val = $this->reduce($val, $inExp); } } @@ -4359,62 +4831,170 @@ class Compiler /** * Sorts keyword arguments * - * @param array $prototype - * @param array $args + * @param string $functionName + * @param array $prototypes + * @param array $args * * @return array */ - protected function sortArgs($prototype, $args) + protected function sortNativeFunctionArgs($functionName, $prototypes, $args) { - $keyArgs = []; - $posArgs = []; + static $parser = null; - // separate positional and keyword arguments - foreach ($args as $arg) { - list($key, $value) = $arg; + if (! isset($prototypes)) { + $keyArgs = []; + $posArgs = []; - $key = $key[1]; + // separate positional and keyword arguments + foreach ($args as $arg) { + list($key, $value) = $arg; - if (empty($key)) { - $posArgs[] = empty($arg[2]) ? $value : $arg; - } else { - $keyArgs[$key] = $value; + $key = $key[1]; + + if (empty($key)) { + $posArgs[] = empty($arg[2]) ? $value : $arg; + } else { + $keyArgs[$key] = $value; + } } - } - if (! isset($prototype)) { return [$posArgs, $keyArgs]; } - // copy positional args - $finalArgs = array_pad($posArgs, count($prototype), null); + // 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]); - // overwrite positional args with keyword args - foreach ($prototype as $i => $names) { - foreach ((array) $names as $name) { - if (isset($keyArgs[$name])) { - $finalArgs[$i] = $keyArgs[$name]; + 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))) { + $prototypes = [$prototypes]; + } + + $keyArgs = []; + + // trying each prototypes + $prototypeHasMatch = false; + $exceptionMessage = ''; + + foreach ($prototypes as $prototype) { + $argDef = []; + + foreach ($prototype as $i => $p) { + $default = null; + $p = explode(':', $p, 2); + $name = array_shift($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)) { + $parser = $this->parserFactory(__METHOD__); + } + + $parser->parseValue($p, $default); + } + } + + $isVariable = false; + + if (substr($name, -3) === '...') { + $isVariable = true; + $name = substr($name, 0, -3); + } + + $argDef[] = [$name, $default, $isVariable]; + } + + try { + $vars = $this->applyArguments($argDef, $args, false, false); + + // ensure all args are populated + foreach ($prototype as $i => $p) { + $name = explode(':', $p)[0]; + + if (! isset($finalArgs[$i])) { + $finalArgs[$i] = null; + } + } + + // apply positional args + foreach (array_values($vars) as $i => $val) { + $finalArgs[$i] = $val; + } + + $keyArgs = array_merge($keyArgs, $vars); + $prototypeHasMatch = true; + + // overwrite positional args with keyword args + foreach ($prototype as $i => $p) { + $name = explode(':', $p)[0]; + + if (isset($keyArgs[$name])) { + $finalArgs[$i] = $keyArgs[$name]; + } + + // special null value as default: translate to real null here + if ($finalArgs[$i] === [Type::T_KEYWORD, 'null']) { + $finalArgs[$i] = null; + } + } + // should we break if this prototype seems fulfilled? + } catch (CompilerException $e) { + $exceptionMessage = $e->getMessage(); + } + } + + if ($exceptionMessage && ! $prototypeHasMatch) { + $this->throwError($exceptionMessage); + } + return [$finalArgs, $keyArgs]; } /** * Apply argument values per definition * - * @param array $argDef - * @param array $argValues + * @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) + protected function applyArguments($argDef, $argValues, $storeInEnv = true, $reduce = true) { - $storeEnv = $this->getStoreEnv(); + $output = []; + if (is_array($argValues) && count($argValues) && end($argValues) === static::$null) { + array_pop($argValues); + } - $env = new Environment; - $env->store = $storeEnv->store; + if ($storeInEnv) { + $storeEnv = $this->getStoreEnv(); + + $env = new Environment; + $env->store = $storeEnv->store; + } $hasVariable = false; $args = []; @@ -4426,37 +5006,64 @@ class Compiler $hasVariable |= $isVariable; } - $keywordArgs = []; + $splatSeparator = null; + $keywordArgs = []; $deferredKeywordArgs = []; - $remaining = []; + $remaining = []; + $hasKeywordArgument = false; // assign the keyword args foreach ((array) $argValues as $arg) { if (! empty($arg[0])) { - if (! isset($args[$arg[0][1]])) { + $hasKeywordArgument = true; + + $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 (count($keywordArgs)) { - $this->throwError('Positional arguments must come before keyword arguments.'); - break; } elseif ($arg[2] === true) { $val = $this->reduce($arg[1], true); if ($val[0] === Type::T_LIST) { foreach ($val[2] as $name => $item) { if (! is_numeric($name)) { - $keywordArgs[$name] = $item; + if (! isset($args[$name])) { + foreach (array_keys($args) as $an) { + if (str_replace("_", "-", $an) === str_replace("_", "-", $name)) { + $name = $an; + break; + } + } + } + + if ($hasVariable) { + $deferredKeywordArgs[$name] = $item; + } else { + $keywordArgs[$name] = $item; + } } else { + if (is_null($splatSeparator)) { + $splatSeparator = $val[1]; + } + $remaining[] = $item; } } @@ -4466,14 +5073,34 @@ class Compiler $item = $val[2][$i]; if (! is_numeric($name)) { - $keywordArgs[$name] = $item; + if (! isset($args[$name])) { + foreach (array_keys($args) as $an) { + if (str_replace("_", "-", $an) === str_replace("_", "-", $name)) { + $name = $an; + break; + } + } + } + + if ($hasVariable) { + $deferredKeywordArgs[$name] = $item; + } else { + $keywordArgs[$name] = $item; + } } else { + if (is_null($splatSeparator)) { + $splatSeparator = $val[1]; + } + $remaining[] = $item; } } } else { $remaining[] = $val; } + } elseif ($hasKeywordArgument) { + $this->throwError('Positional arguments must come before keyword arguments.'); + break; } else { $remaining[] = $arg[1]; } @@ -4483,7 +5110,7 @@ class Compiler list($i, $name, $default, $isVariable) = $arg; if ($isVariable) { - $val = [Type::T_LIST, ',', [], $isVariable]; + $val = [Type::T_LIST, is_null($splatSeparator) ? ',' : $splatSeparator , [], $isVariable]; for ($count = count($remaining); $i < $count; $i++) { $val[2][] = $remaining[$i]; @@ -4503,10 +5130,16 @@ class Compiler break; } - $this->set($name, $this->reduce($val, true), true, $env); + if ($storeInEnv) { + $this->set($name, $this->reduce($val, true), true, $env); + } else { + $output[$name] = ($reduce ? $this->reduce($val, true) : $val); + } } - $storeEnv->store = $env->store; + if ($storeInEnv) { + $storeEnv->store = $env->store; + } foreach ($args as $arg) { list($i, $name, $default, $isVariable) = $arg; @@ -4515,8 +5148,14 @@ class Compiler continue; } - $this->set($name, $this->reduce($default, true), true); + if ($storeInEnv) { + $this->set($name, $this->reduce($default, true), true); + } else { + $output[$name] = ($reduce ? $this->reduce($default, true) : $default); + } } + + return $output; } /** @@ -4536,7 +5175,7 @@ class Compiler return $this->toBool($value); } - if ($value === null) { + if (is_null($value)) { return static::$null; } @@ -4548,30 +5187,14 @@ class Compiler 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; } /** @@ -4587,7 +5210,9 @@ class Compiler 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; } @@ -4617,10 +5242,21 @@ class Compiler $key = $keys[$i]; $value = $values[$i]; + switch ($key[0]) { + case Type::T_LIST: + case Type::T_MAP: + case Type::T_STRING: + break; + + default: + $key = [Type::T_KEYWORD, $this->compileStringContent($this->coerceString($key))]; + break; + } + $list[] = [ Type::T_LIST, '', - [[Type::T_KEYWORD, $this->compileStringContent($this->coerceString($key))], $value] + [$key, $value] ]; } @@ -4653,21 +5289,106 @@ class Compiler * * @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]); + // hexa color? + if (preg_match('/^#([0-9a-f]+)$/i', $name, $m)) { + $nofValues = strlen($m[1]); - if (isset(Colors::$cssColors[$name])) { - $rgba = explode(',', Colors::$cssColors[$name]); + 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; @@ -4676,6 +5397,88 @@ class Compiler 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 * @@ -4923,46 +5726,27 @@ class Compiler // Built in functions - //protected static $libCall = ['name', 'args...']; + protected static $libCall = ['name', 'args...']; protected function libCall($args, $kwargs) { $name = $this->compileStringContent($this->coerceString($this->reduce(array_shift($args), true))); + $callArgs = []; - $posArgs = []; - - foreach ($args as $arg) { - if (empty($arg[0])) { - if ($arg[2] === true) { - $tmp = $this->reduce($arg[1]); - - if ($tmp[0] === Type::T_LIST) { - foreach ($tmp[2] as $item) { - $posArgs[] = [null, $item, false]; - } - } else { - $posArgs[] = [null, $tmp, true]; - } - - continue; - } - - $posArgs[] = [null, $this->reduce($arg), false]; - continue; + // $kwargs['args'] is [Type::T_LIST, ',', [..]] + foreach ($kwargs['args'][2] as $varname => $arg) { + if (is_numeric($varname)) { + $varname = null; + } else { + $varname = [ 'var', $varname]; } - $posArgs[] = [null, $arg, false]; + $callArgs[] = [$varname, $arg, false]; } - if (count($kwargs)) { - foreach ($kwargs as $key => $value) { - $posArgs[] = [[Type::T_VARIABLE, $key], $value, false]; - } - } - - return $this->reduce([Type::T_FUNCTION_CALL, $name, $posArgs]); + return $this->reduce([Type::T_FUNCTION_CALL, $name, $callArgs]); } - protected static $libIf = ['condition', 'if-true', 'if-false']; + protected static $libIf = ['condition', 'if-true', 'if-false:']; protected function libIf($args) { list($cond, $t, $f) = $args; @@ -5006,30 +5790,68 @@ class Compiler 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]]; + + if (! $color = $this->coerceColor($color)) { + $color = [Type::T_STRING, '', [$funcName .'(', $args[0], ', ', $args[1], ', ', $args[2], ')']]; + } + + 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; + } + + return $color; } protected static $libRgba = [ - ['red', 'color'], - 'green', 'blue', 'alpha']; - protected function libRgba($args) + ['color'], + ['color', 'alpha'], + ['channels'], + ['red', 'green', 'blue'], + ['red', 'green', 'blue', 'alpha'] ]; + protected function libRgba($args, $kwargs) { - if ($color = $this->coerceColor($args[0])) { - $num = isset($args[3]) ? $args[3] : $args[1]; - $alpha = $this->assertNumber($num); - $color[4] = $alpha; - - return $color; - } - - list($r, $g, $b, $a) = $args; - - return [Type::T_COLOR, $r[1], $g[1], $b[1], $a[1]]; + return $this->libRgb($args, $kwargs, 'rgba'); } // helper function for adjust_color, change_color, and scale_color @@ -5037,21 +5859,25 @@ class Compiler { $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 (isset($args[4]) || isset($args[5]) || isset($args[6])) { + 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 (isset($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); } } @@ -5068,8 +5894,8 @@ class Compiler } protected static $libAdjustColor = [ - 'color', 'red', 'green', 'blue', - 'hue', 'saturation', 'lightness', 'alpha' + 'color', 'red:null', 'green:null', 'blue:null', + 'hue:null', 'saturation:null', 'lightness:null', 'alpha:null' ]; protected function libAdjustColor($args) { @@ -5079,8 +5905,8 @@ class Compiler } protected static $libChangeColor = [ - 'color', 'red', 'green', 'blue', - 'hue', 'saturation', 'lightness', 'alpha' + 'color', 'red:null', 'green:null', 'blue:null', + 'hue:null', 'saturation:null', 'lightness:null', 'alpha:null' ]; protected function libChangeColor($args) { @@ -5090,8 +5916,8 @@ class Compiler } protected static $libScaleColor = [ - 'color', 'red', 'green', 'blue', - 'hue', 'saturation', 'lightness', 'alpha' + 'color', 'red:null', 'green:null', 'blue:null', + 'hue:null', 'saturation:null', 'lightness:null', 'alpha:null' ]; protected function libScaleColor($args) { @@ -5134,7 +5960,7 @@ class Compiler $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']; @@ -5185,7 +6011,7 @@ class Compiler } // mix two colors - protected static $libMix = ['color-1', 'color-2', 'weight']; + protected static $libMix = ['color-1', 'color-2', 'weight:0.5']; protected function libMix($args) { list($first, $second, $weight) = $args; @@ -5221,25 +6047,56 @@ class Compiler 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); - $color = $this->toRGB($h[1], $s[1], $l[1]); - $color[4] = $a[1]; + $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($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) { @@ -5307,7 +6164,7 @@ class Compiler return $this->adjustHsl($color, 3, -$amount); } - protected static $libSaturate = ['color', 'amount']; + protected static $libSaturate = [['color', 'amount'], ['number']]; protected function libSaturate($args) { $value = $args[0]; @@ -5349,21 +6206,32 @@ class Compiler 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 @@ -5472,7 +6340,7 @@ class Compiler $min = null; foreach ($numbers as $key => $number) { - if (null === $min || $number[1] <= $min[1]) { + if (is_null($min) || $number[1] <= $min[1]) { $min = [$key, $number[1]]; } } @@ -5486,7 +6354,7 @@ class Compiler $max = null; foreach ($numbers as $key => $number) { - if (null === $max || $number[1] >= $max[1]) { + if (is_null($max) || $number[1] >= $max[1]) { $max = [$key, $number[1]]; } } @@ -5503,9 +6371,9 @@ class Compiler */ protected function getNormalizedNumbers($args) { - $unit = null; + $unit = null; $originalUnit = null; - $numbers = []; + $numbers = []; foreach ($args as $key => $item) { if ($item[0] !== Type::T_NUMBER) { @@ -5515,7 +6383,7 @@ class Compiler $number = $item->normalize(); - if (null === $unit) { + if (is_null($unit)) { $unit = $number[2]; $originalUnit = $item->unitStr(); } elseif ($number[1] && $unit !== $number[2]) { @@ -5599,11 +6467,15 @@ class Compiler protected function libMapGet($args) { $map = $this->assertMap($args[0]); - $key = $this->compileStringContent($this->coerceString($args[1])); + $key = $args[1]; - for ($i = count($map[1]) - 1; $i >= 0; $i--) { - if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) { - return $map[2][$i]; + if (! is_null($key)) { + $key = $this->compileStringContent($this->coerceString($key)); + + for ($i = count($map[1]) - 1; $i >= 0; $i--) { + if ($key === $this->compileStringContent($this->coerceString($map[1][$i]))) { + return $map[2][$i]; + } } } @@ -5698,6 +6570,18 @@ class Compiler 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)) { @@ -5709,26 +6593,56 @@ class Compiler return ','; case 'space': - return ''; + return ' '; default: return $list1[1]; } } - protected static $libJoin = ['list1', 'list2', 'separator']; + 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); + $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']; + protected static $libAppend = ['list', 'val', 'separator:null']; protected function libAppend($args) { list($list1, $value, $sep) = $args; @@ -5736,13 +6650,17 @@ class Compiler $list1 = $this->coerceList($list1, ' '); $sep = $this->listSeparatorForJoin($list1, $sep); - return [Type::T_LIST, $sep, array_merge($list1[2], [$value])]; + $res = [Type::T_LIST, $sep, array_merge($list1[2], [$value])]; + if (isset($list1['enclosing'])) { + $res['enclosing'] = $list1['enclosing']; + } + return $res; } protected function libZip($args) { - foreach ($args as $arg) { - $this->assertList($arg); + foreach ($args as $key => $arg) { + $args[$key] = $this->coerceList($arg); } $lists = []; @@ -5873,10 +6791,10 @@ class Compiler return new Node\Number(strlen($stringContent), ''); } - protected static $libStrSlice = ['string', 'start-at', 'end-at']; + protected static $libStrSlice = ['string', 'start-at', 'end-at:-1']; protected function libStrSlice($args) { - if (isset($args[2]) && $args[2][1] == 0) { + if (isset($args[2]) && ! $args[2][1]) { return static::$nullString; } @@ -5889,7 +6807,7 @@ class Compiler $start--; } - $end = (int) $args[2][1]; + $end = isset($args[2]) ? (int) $args[2][1] : -1; $length = $end < 0 ? $end + 1 : ($end > 0 ? $end - $start : $end); $string[2] = $length @@ -6027,14 +6945,40 @@ class Compiler 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'])) { + if ($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']; - } - - return $args[0]; + $value = $args[0]; + return $this->inspectFormatValue($value); } /** @@ -6182,9 +7126,13 @@ class Compiler return true; } - //protected static $libSelectorAppend = ['selector...']; + protected static $libSelectorAppend = ['selector...']; protected function libSelectorAppend($args) { + // get the selector... list + $args = reset($args); + $args = $args[2]; + if (count($args) < 1) { $this->throwError("selector-append() needs at least 1 argument"); } @@ -6251,8 +7199,8 @@ class Compiler 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"); @@ -6268,8 +7216,8 @@ class Compiler { 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) { @@ -6328,16 +7276,20 @@ class Compiler return $extended; } - //protected static $libSelectorNest = ['selector...']; + protected static $libSelectorNest = ['selector...']; protected function libSelectorNest($args) { + // get the selector... list + $args = reset($args); + $args = $args[2]; + 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; @@ -6345,8 +7297,8 @@ class Compiler $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); @@ -6389,6 +7341,7 @@ class Compiler * * @param array $compound1 * @param array $compound2 + * * @return array|mixed */ protected function unifyCompoundSelectors($compound1, $compound2) @@ -6404,7 +7357,7 @@ class Compiler // 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 [[]]; @@ -6427,6 +7380,7 @@ class Compiler $c = $this->mergeParts($part1, $part2); $unifiedSelectors = $this->prependSelectors($unifiedSelectors, [$c]); + $part1 = $part2 = null; array_pop($compound1); @@ -6441,6 +7395,7 @@ class Compiler $c = $this->mergeParts($part2, $part1); $unifiedSelectors = $this->prependSelectors($unifiedSelectors, [$c]); + $part1 = $part2 = null; array_pop($compound2); @@ -6452,9 +7407,9 @@ class Compiler 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); @@ -6508,8 +7463,8 @@ class Compiler 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)) { @@ -6555,7 +7510,7 @@ class Compiler { $tag1 = $this->findTagName($parts1); $tag2 = $this->findTagName($parts2); - $tag = $this->checkCompatibleTags($tag1, $tag2); + $tag = $this->checkCompatibleTags($tag1, $tag2); // not compatible tags if ($tag === false) { @@ -6606,12 +7561,12 @@ class Compiler $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; } diff --git a/lib/scssphp/scssphp/src/Formatter.php b/lib/scssphp/scssphp/src/Formatter.php index b2efc2dcb..e17770458 100644 --- a/lib/scssphp/scssphp/src/Formatter.php +++ b/lib/scssphp/scssphp/src/Formatter.php @@ -81,6 +81,11 @@ abstract class Formatter */ protected $sourceMapGenerator; + /** + * @var string + */ + protected $strippedSemicolon; + /** * Initialize formatter * @@ -113,26 +118,6 @@ abstract class Formatter return rtrim($name) . $this->assignSeparator . $value . ';'; } - /** - * Strip semi-colon appended by property(); it's a separator, not a terminator - * - * @api - * - * @param array $lines - */ - public function stripSemicolon(&$lines) - { - if ($this->keepSemicolons) { - return; - } - - if (($count = count($lines)) - && substr($lines[$count - 1], -1) === ';' - ) { - $lines[$count - 1] = substr($lines[$count - 1], 0, -1); - } - } - /** * Output lines inside a block * @@ -209,6 +194,10 @@ abstract class Formatter if (! empty($block->selectors)) { $this->indentLevel--; + if (! $this->keepSemicolons) { + $this->strippedSemicolon = ''; + } + if (empty($block->children)) { $this->write($this->break); } @@ -217,6 +206,34 @@ abstract class Formatter } } + /** + * Test and clean safely empty children + * + * @param \ScssPhp\ScssPhp\Formatter\OutputBlock $block + * + * @return boolean + */ + protected function testEmptyChildren($block) + { + $isEmpty = empty($block->lines); + + if ($block->children) { + foreach ($block->children as $k => &$child) { + if (! $this->testEmptyChildren($child)) { + $isEmpty = false; + continue; + } + + if ($child->type === Type::T_MEDIA || $child->type === Type::T_DIRECTIVE) { + $child->children = []; + $child->selectors = null; + } + } + } + + return $isEmpty; + } + /** * Entry point to formatting a block * @@ -232,11 +249,13 @@ abstract class Formatter $this->sourceMapGenerator = null; if ($sourceMapGenerator) { - $this->currentLine = 1; - $this->currentColumn = 0; + $this->currentLine = 1; + $this->currentColumn = 0; $this->sourceMapGenerator = $sourceMapGenerator; } + $this->testEmptyChildren($block); + ob_start(); $this->block($block); @@ -247,10 +266,32 @@ abstract class Formatter } /** + * 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, diff --git a/lib/scssphp/scssphp/src/Formatter/Expanded.php b/lib/scssphp/scssphp/src/Formatter/Expanded.php index 8eec47587..9549c6cfa 100644 --- a/lib/scssphp/scssphp/src/Formatter/Expanded.php +++ b/lib/scssphp/scssphp/src/Formatter/Expanded.php @@ -55,7 +55,7 @@ class Expanded extends Formatter 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/lib/scssphp/scssphp/src/Formatter/Nested.php b/lib/scssphp/scssphp/src/Formatter/Nested.php index 260ae8e7a..f9e7f037f 100644 --- a/lib/scssphp/scssphp/src/Formatter/Nested.php +++ b/lib/scssphp/scssphp/src/Formatter/Nested.php @@ -13,6 +13,7 @@ namespace ScssPhp\ScssPhp\Formatter; use ScssPhp\ScssPhp\Formatter; use ScssPhp\ScssPhp\Formatter\OutputBlock; +use ScssPhp\ScssPhp\Type; /** * Nested formatter @@ -62,49 +63,11 @@ class Nested extends Formatter 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)); - - if (! empty($block->children)) { - $this->write($this->break); - } - } - - /** - * {@inheritdoc} - */ - protected function blockSelectors(OutputBlock $block) - { - $inner = $this->indentStr(); - - $this->write($inner - . implode($this->tagSeparator, $block->selectors) - . $this->open . $this->break); - } - - /** - * {@inheritdoc} - */ - protected function blockChildren(OutputBlock $block) - { - foreach ($block->children as $i => $child) { - $this->block($child); - - if ($i < count($block->children) - 1) { - $this->write($this->break); - - if (isset($block->children[$i + 1])) { - $next = $block->children[$i + 1]; - - if ($next->depth === max($block->depth, 1) && $child->depth >= $next->depth) { - $this->write($this->break); - } - } - } - } } /** @@ -112,8 +75,38 @@ class Nested extends Formatter */ protected function block(OutputBlock $block) { + static $depths; + static $downLevel; + static $closeBlock; + static $previousEmpty; + static $previousHasSelector; + if ($block->type === 'root') { - $this->adjustAllChildren($block); + $depths = [ 0 ]; + $downLevel = ''; + $closeBlock = ''; + $this->depth = 0; + $previousEmpty = false; + $previousHasSelector = false; + } + + $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); + + while ($block->depth < end($depths) || ($block->depth == 1 && end($depths) == 1)) { + array_pop($depths); + $this->depth--; + + if (! $this->depth && ($block->depth <= 1 || (! $this->indentLevel && $block->type === Type::T_COMMENT)) && + (($block->selectors && ! $isMediaOrDirective) || $previousHasSelector) + ) { + $downLevel = $this->break; + } + + if (empty($block->lines) && empty($block->children)) { + $previousEmpty = true; + } } if (empty($block->lines) && empty($block->children)) { @@ -122,27 +115,92 @@ class Nested extends Formatter $this->currentBlock = $block; + if (! empty($block->lines) || (! empty($block->children) && ($this->depth < 1 || $isSupport))) { + 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; + } + } + } - $this->depth = $block->depth; + $previousEmpty = ($block->type === Type::T_COMMENT); + $previousHasSelector = false; if (! empty($block->selectors)) { + if ($closeBlock) { + $this->write($closeBlock); + $closeBlock = ''; + } + + if ($downLevel) { + $this->write($downLevel); + $downLevel = ''; + } + $this->blockSelectors($block); $this->indentLevel++; } if (! empty($block->lines)) { + if ($closeBlock) { + $this->write($closeBlock); + $closeBlock = ''; + } + + if ($downLevel) { + $this->write($downLevel); + $downLevel = ''; + } + $this->blockLines($block); + + $closeBlock = $this->break; } if (! empty($block->children)) { - $this->blockChildren($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); + } + } + + // reclear to not be spoiled by children if T_DIRECTIVE + if ($block->type === Type::T_DIRECTIVE) { + $previousHasSelector = false; } 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; + } } if ($block->type === 'root') { @@ -151,51 +209,20 @@ class Nested extends Formatter } /** - * Adjust the depths of all children, depth first + * Block has flat child * * @param \ScssPhp\ScssPhp\Formatter\OutputBlock $block + * + * @return boolean */ - private function adjustAllChildren(OutputBlock $block) + private function hasFlatChild($block) { - // flatten empty nested blocks - $children = []; - - foreach ($block->children as $i => $child) { - if (empty($child->lines) && empty($child->children)) { - if (isset($block->children[$i + 1])) { - $block->children[$i + 1]->depth = $child->depth; - } - - continue; - } - - $children[] = $child; - } - - $count = count($children); - - for ($i = 0; $i < $count; $i++) { - $depth = $children[$i]->depth; - $j = $i + 1; - - if (isset($children[$j]) && $depth < $children[$j]->depth) { - $childDepth = $children[$j]->depth; - - for (; $j < $count; $j++) { - if ($depth < $children[$j]->depth && $childDepth >= $children[$j]->depth) { - $children[$j]->depth = $depth + 1; - } - } - } - } - - $block->children = $children; - - // make relative to parent foreach ($block->children as $child) { - $this->adjustAllChildren($child); - - $child->depth = $child->depth - $block->depth; + if (empty($child->selectors)) { + return true; + } } + + return false; } } diff --git a/lib/scssphp/scssphp/src/Node/Number.php b/lib/scssphp/scssphp/src/Node/Number.php index e184ca193..acbabff7f 100644 --- a/lib/scssphp/scssphp/src/Node/Number.php +++ b/lib/scssphp/scssphp/src/Node/Number.php @@ -141,17 +141,17 @@ class Number extends Node implements \ArrayAccess 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 - || $offset === 0 - || $offset === 1 - || $offset === 2 + if ($offset === -1 || + $offset === 0 || + $offset === 1 || + $offset === 2 ) { return true; } diff --git a/lib/scssphp/scssphp/src/Parser.php b/lib/scssphp/scssphp/src/Parser.php index b8091313b..6a30af129 100644 --- a/lib/scssphp/scssphp/src/Parser.php +++ b/lib/scssphp/scssphp/src/Parser.php @@ -64,6 +64,7 @@ class Parser private $env; private $inParens; private $eatWhiteDefault; + private $discardComments; private $buffer; private $utf8; private $encoding; @@ -88,6 +89,7 @@ class Parser $this->utf8 = ! $encoding || strtolower($encoding) === 'utf-8'; $this->patternModifiers = $this->utf8 ? 'Aisu' : 'Ais'; $this->commentsSeen = []; + $this->discardComments = false; if (empty(static::$operatorPattern)) { static::$operatorPattern = '([*\/%+-]|[!=]\=|\>\=?|\<\=\>|\<\=?|and|or)'; @@ -216,8 +218,8 @@ class Parser * * @api * - * @param string $buffer - * @param string $out + * @param string $buffer + * @param string|array $out * * @return boolean */ @@ -243,8 +245,8 @@ class Parser * * @api * - * @param string $buffer - * @param string $out + * @param string $buffer + * @param string|array $out * * @return boolean */ @@ -265,6 +267,33 @@ class Parser return $selector; } + /** + * Parse a media Query + * + * @api + * + * @param string $buffer + * @param string|array $out + * + * @return boolean + */ + public function parseMediaQueryList($buffer, &$out) + { + $this->count = 0; + $this->env = null; + $this->inParens = false; + $this->eatWhiteDefault = true; + $this->buffer = (string) $buffer; + + $this->saveEncoding(); + + $isMediaQuery = $this->mediaQueryList($out); + + $this->restoreEncoding(); + + return $isMediaQuery; + } + /** * Parse a single chunk off the head of the buffer and append it to the * current parse environment. @@ -313,18 +342,21 @@ class Parser if ($this->literal('@at-root', 8) && ($this->selectors($selector) || true) && ($this->map($with) || true) && - $this->matchChar('{') + (($this->matchChar('(') + && $this->interpolation($with) + && $this->matchChar(')')) || true) && + $this->matchChar('{', false) ) { $atRoot = $this->pushSpecialBlock(Type::T_AT_ROOT, $s); $atRoot->selector = $selector; - $atRoot->with = $with; + $atRoot->with = $with; return true; } $this->seek($s); - if ($this->literal('@media', 6) && $this->mediaQueryList($mediaQueryList) && $this->matchChar('{')) { + if ($this->literal('@media', 6) && $this->mediaQueryList($mediaQueryList) && $this->matchChar('{', false)) { $media = $this->pushSpecialBlock(Type::T_MEDIA, $s); $media->queryList = $mediaQueryList[2]; @@ -336,7 +368,7 @@ class Parser if ($this->literal('@mixin', 6) && $this->keyword($mixinName) && ($this->argumentDef($args) || true) && - $this->matchChar('{') + $this->matchChar('{', false) ) { $mixin = $this->pushSpecialBlock(Type::T_MIXIN, $s); $mixin->name = $mixinName; @@ -353,9 +385,18 @@ class Parser ($this->argValues($argValues) || true) && $this->matchChar(')') || true) && ($this->end() || + ($this->literal('using', 5) && + $this->argumentDef($argUsing) && + ($this->end() || $this->matchChar('{') && $hasBlock = true)) || $this->matchChar('{') && $hasBlock = true) ) { - $child = [Type::T_INCLUDE, $mixinName, isset($argValues) ? $argValues : null, null]; + $child = [ + Type::T_INCLUDE, + $mixinName, + isset($argValues) ? $argValues : null, + null, + isset($argUsing) ? $argUsing : null + ]; if (! empty($hasBlock)) { $include = $this->pushSpecialBlock(Type::T_INCLUDE, $s); @@ -418,7 +459,7 @@ class Parser if ($this->literal('@function', 9) && $this->keyword($fnName) && $this->argumentDef($args) && - $this->matchChar('{') + $this->matchChar('{', false) ) { $func = $this->pushSpecialBlock(Type::T_FUNCTION, $s); $func->name = $fnName; @@ -457,7 +498,7 @@ class Parser $this->genericList($varNames, 'variable', ',', false) && $this->literal('in', 2) && $this->valueList($list) && - $this->matchChar('{') + $this->matchChar('{', false) ) { $each = $this->pushSpecialBlock(Type::T_EACH, $s); @@ -474,7 +515,7 @@ class Parser if ($this->literal('@while', 6) && $this->expression($cond) && - $this->matchChar('{') + $this->matchChar('{', false) ) { $while = $this->pushSpecialBlock(Type::T_WHILE, $s); $while->cond = $cond; @@ -491,12 +532,12 @@ class Parser ($this->literal('through', 7) || ($forUntil = true && $this->literal('to', 2))) && $this->expression($end) && - $this->matchChar('{') + $this->matchChar('{', false) ) { $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; @@ -504,9 +545,15 @@ class Parser $this->seek($s); - if ($this->literal('@if', 3) && $this->valueList($cond) && $this->matchChar('{')) { + if ($this->literal('@if', 3) && $this->valueList($cond) && $this->matchChar('{', false)) { $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; @@ -547,8 +594,15 @@ class Parser $this->seek($s); - if ($this->literal('@content', 8) && $this->end()) { - $this->append([Type::T_MIXIN_CONTENT], $s); + #if ($this->literal('@content', 8)) + + if ($this->literal('@content', 8) && + ($this->end() || + $this->matchChar('(') && + $this->argValues($argContent) && + $this->matchChar(')') && + $this->end())) { + $this->append([Type::T_MIXIN_CONTENT, isset($argContent) ? $argContent : null], $s); return true; } @@ -561,9 +615,9 @@ class Parser list(, $if) = $last; if ($this->literal('@else', 5)) { - if ($this->matchChar('{')) { + if ($this->matchChar('{', false)) { $else = $this->pushSpecialBlock(Type::T_ELSE, $s); - } elseif ($this->literal('if', 2) && $this->valueList($cond) && $this->matchChar('{')) { + } elseif ($this->literal('if', 2) && $this->valueList($cond) && $this->matchChar('{', false)) { $else = $this->pushSpecialBlock(Type::T_ELSEIF, $s); $else->cond = $cond; } @@ -601,11 +655,24 @@ class Parser $this->seek($s); + if ($this->literal('@supports', 9) && + ($t1=$this->supportsQuery($supportQuery)) && + ($t2=$this->matchChar('{', false)) + ) { + $directive = $this->pushSpecialBlock(Type::T_DIRECTIVE, $s); + $directive->name = 'supports'; + $directive->value = $supportQuery; + + return true; + } + + $this->seek($s); + // 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('{') + $this->matchChar('{', false) ) { if ($dirName === 'media') { $directive = $this->pushSpecialBlock(Type::T_MEDIA, $s); @@ -623,6 +690,19 @@ class Parser $this->seek($s); + // maybe it's a generic blockless directive + if ($this->matchChar('@', false) && + $this->keyword($dirName) && + $this->valueList($dirValue) && + $this->end() + ) { + $this->append([Type::T_DIRECTIVE, [$dirName, $dirValue]], $s); + + return true; + } + + $this->seek($s); + return false; } @@ -667,7 +747,7 @@ class Parser 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; @@ -688,9 +768,11 @@ class Parser $foundSomething = true; } - if ($this->matchChar('{')) { + if ($this->matchChar('{', false)) { $propBlock = $this->pushSpecialBlock(Type::T_NESTED_PROPERTY, $s); $propBlock->prefix = $name; + $propBlock->hasValue = $foundSomething; + $foundSomething = true; } elseif ($foundSomething) { $foundSomething = $this->end(); @@ -704,9 +786,15 @@ class Parser $this->seek($s); // closing a block - if ($this->matchChar('}')) { + if ($this->matchChar('}', false)) { $block = $this->popBlock(); + if (! isset($block->type) || $block->type !== Type::T_IF) { + if ($this->env->parent) { + $this->append(null); // collect comments before next statement if needed + } + } + if (isset($block->type) && $block->type === Type::T_INCLUDE) { $include = $block->child; unset($block->child); @@ -717,6 +805,15 @@ class Parser $this->append([$type, $block], $s); } + // collect comments just after the block closing if needed + if ($this->eatWhiteDefault) { + $this->whitespace(); + + if ($this->env->comments) { + $this->append(null); + } + } + return true; } @@ -764,6 +861,15 @@ class Parser $this->env = $b; + // collect comments at the beginning of a block if needed + if ($this->eatWhiteDefault) { + $this->whitespace(); + + if ($this->env->comments) { + $this->append(null); + } + } + return $b; } @@ -792,6 +898,13 @@ class Parser */ protected function popBlock() { + + // collect comments ending just before of a block closing + if ($this->env->comments) { + $this->append(null); + } + + // pop the block $block = $this->env; if (empty($block->parent)) { @@ -807,13 +920,6 @@ class Parser unset($block->parent); - $comments = $block->comments; - - if ($comments) { - $this->env->comments = $comments; - unset($block->comments); - } - return $block; } @@ -987,16 +1093,17 @@ class Parser if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { // comment that are kept in the output CSS $comment = []; + $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 @@ -1008,7 +1115,7 @@ class Parser $out[3] = ''; } - $comment[] = $out; + $comment[] = [Type::T_COMMENT, substr($this->buffer, $p, $this->count - $p), $out]; } else { $comment[] = substr($this->buffer, $this->count, 2); @@ -1026,10 +1133,11 @@ class Parser $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 @@ -1049,11 +1157,26 @@ class Parser */ protected function appendComment($comment) { - if ($comment[0] === Type::T_COMMENT && is_string($comment[1])) { - $comment[1] = substr(preg_replace(['/^\s+/m', '/^(.)/m'], ['', ' \1'], $comment[1]), 1); - } + if (! $this->discardComments) { + 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; + $this->env->comments[] = $comment; + } } /** @@ -1065,7 +1188,7 @@ class Parser protected function append($statement, $pos = null) { if (! is_null($statement)) { - if ($pos !== null) { + if (! is_null($pos)) { list($line, $column) = $this->getSourcePosition($pos); $statement[static::SOURCE_LINE] = $line; @@ -1162,6 +1285,130 @@ class Parser return true; } + /** + * Parse supports query + * + * @param array $out + * + * @return boolean + */ + protected function supportsQuery(&$out) + { + $expressions = null; + $parts = []; + + $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(')') + ) { + $support = [Type::T_STRING, '', [[Type::T_KEYWORD, ($not ? 'not ' : '') . '(']]]; + $support[2][] = $property; + $support[2][] = [Type::T_KEYWORD, ': ']; + $support[2][] = $value; + $support[2][] = [Type::T_KEYWORD, ')']; + + $parts[] = $support; + $s = $this->count; + } else { + $this->seek($s); + } + + if ($this->matchChar('(') && + $this->supportsQuery($subQuery) && + $this->matchChar(')') + ) { + $parts[] = [Type::T_STRING, '', [[Type::T_KEYWORD, '('], $subQuery, [Type::T_KEYWORD, ')']]]; + $s = $this->count; + } else { + $this->seek($s); + } + + if ($this->literal('not', 3) && + $this->supportsQuery($subQuery) + ) { + $parts[] = [Type::T_STRING, '', [[Type::T_KEYWORD, 'not '], $subQuery]]; + $s = $this->count; + } else { + $this->seek($s); + } + + if ($this->literal('selector(', 9) && + $this->selector($selector) && + $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)) { + $compound[2][] = $scp; + } else { + $compound[2][] = [Type::T_KEYWORD, $scp]; + } + } + + $selectorList[2][] = $compound; + } + $support[2][] = $selectorList; + $support[2][] = [Type::T_KEYWORD, ')']; + $parts[] = $support; + $s = $this->count; + } else { + $this->seek($s); + } + + if ($this->variable($var) or $this->interpolation($var)) { + $parts[] = $var; + $s = $this->count; + } else { + $this->seek($s); + } + + 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 { + $this->seek($s); + } + + 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 ($this->eatWhiteDefault) { + $this->whitespace(); + } + + $out = [Type::T_STRING, '', $parts]; + + return true; + } + + return false; + } + + /** * Parse media expression * @@ -1226,6 +1473,7 @@ class Parser if (! $this->variable($keyword) || ! $this->matchChar(':')) { $this->seek($s); + $keyword = null; } @@ -1254,7 +1502,12 @@ class Parser */ protected function valueList(&$out) { - return $this->genericList($out, 'spaceList', ','); + $discardComments = $this->discardComments; + $this->discardComments = true; + $res = $this->genericList($out, 'spaceList', ','); + $this->discardComments = $discardComments; + + return $res; } /** @@ -1281,17 +1534,19 @@ class Parser */ 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))) { break; } + $trailing_delim = true; } } @@ -1301,6 +1556,9 @@ class Parser return false; } + if ($trailing_delim) { + $items[] = [Type::T_NULL]; + } if ($flatten && count($items) === 1) { $out = $items[0]; } else { @@ -1314,39 +1572,62 @@ class Parser * Parse expression * * @param array $out + * @param bool $listOnly + * @param bool $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, ")")) { - 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 ($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->value($lhs)) { - $out = $this->expHelper($lhs, 0); + 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 (!$listOnly && $this->value($lhs)) { + if ($lookForExp) { + $out = $this->expHelper($lhs, 0); + } else { + $out = $lhs; + } + + $this->discardComments = $discard; return true; } + $this->discardComments = $discard; return false; } @@ -1360,15 +1641,35 @@ class Parser * * @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; } @@ -1412,7 +1713,7 @@ class Parser break; } - if (! $this->value($rhs)) { + if (! $this->value($rhs) && ! $this->expression($rhs, true, false)) { break; } @@ -1467,7 +1768,7 @@ class Parser $this->seek($s); - if ($this->literal('url(', 4, false) && $this->match('\s*(\/\/\S+)\s*', $m)) { + if ($this->literal('url(', 4, false) && $this->match('\s*(\/\/[^\s\)]+)\s*', $m)) { $content = 'url(' . $m[1]; if ($this->matchChar(')')) { @@ -1563,6 +1864,7 @@ class Parser // 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; } @@ -1852,55 +2154,16 @@ class Parser */ 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; - - 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 (in_array(strlen($m[2]), [3,4,6,8])) { + $out = [Type::T_KEYWORD, $m[0]]; + return true; } - if ($hasAlpha) { - if ($color[4] === 255) { - $color[4] = 1; // fully opaque - } else { - $color[4] = round($color[4] / 255, 3); - } - } - - $out = $color; - - return true; + $this->seek($s); + return false; } return false; @@ -1978,10 +2241,11 @@ class Parser $content[] = $m[2] . "'"; } 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)) { + } elseif ($this->literal("\r\n", 2, 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]; @@ -2022,11 +2286,12 @@ class Parser /** * Parse keyword or interpolation * - * @param array $out + * @param array $out + * @param boolean $restricted * * @return boolean */ - protected function mixedKeyword(&$out) + protected function mixedKeyword(&$out, $restricted = false) { $parts = []; @@ -2034,7 +2299,7 @@ class Parser $this->eatWhiteDefault = false; for (;;) { - if ($this->keyword($key)) { + if ($restricted ? $this->restrictedKeyword($key) : $this->keyword($key)) { $parts[] = $key; continue; } @@ -2132,8 +2397,8 @@ class Parser /** * 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 */ @@ -2149,7 +2414,7 @@ class Parser $out = $value; } else { if ($lookWhite) { - $left = preg_match('/\s/', $this->buffer[$s - 1]) ? ' ' : ''; + $left = ($s > 0 && preg_match('/\s/', $this->buffer[$s - 1])) ? ' ' : ''; $right = preg_match('/\s/', $this->buffer[$this->count]) ? ' ': ''; } else { $left = $right = false; @@ -2238,7 +2503,8 @@ class Parser /** * Parse comma separated selector list * - * @param array $out + * @param array $out + * @param boolean $subSelector * * @return boolean */ @@ -2273,7 +2539,8 @@ class Parser /** * Parse whitespace separated selector list * - * @param array $out + * @param array $out + * @param boolean $subSelector * * @return boolean */ @@ -2282,9 +2549,17 @@ class Parser $selector = []; for (;;) { + $s = $this->count; + if ($this->match('[>+~]+', $m, true)) { - $selector[] = [$m[0]]; - continue; + if ($subSelector && is_string($subSelector) && strpos($subSelector, 'nth-') === 0 && + $m[0] === '+' && $this->match("(\d+|n\b)", $counter) + ) { + $this->seek($s); + } else { + $selector[] = [$m[0]]; + continue; + } } if ($this->selectorSingle($part, $subSelector)) { @@ -2317,7 +2592,8 @@ class Parser * div[yes=no]#something.hello.world:nth-child(-2n+1)%placeholder * }} * - * @param array $out + * @param array $out + * @param boolean $subSelector * * @return boolean */ @@ -2406,7 +2682,7 @@ class Parser $part = ':'; } - if ($this->mixedKeyword($nameParts)) { + if ($this->mixedKeyword($nameParts, true)) { $parts[] = $part; foreach ($nameParts as $sub) { @@ -2416,10 +2692,13 @@ class Parser $ss = $this->count; if ($nameParts === ['not'] || $nameParts === ['is'] || - $nameParts === ['has'] || $nameParts === ['where'] + $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('(') && - ($this->selectors($subs, true) || true) && + if ($this->matchChar('(', true) && + ($this->selectors($subs, reset($nameParts)) || true) && $this->matchChar(')') ) { $parts[] = '('; @@ -2429,10 +2708,12 @@ class Parser foreach ($ps as &$p) { $parts[] = $p; } + if (count($sub) && reset($sub)) { $parts[] = ' '; } } + if (count($subs) && reset($subs)) { $parts[] = ', '; } @@ -2465,6 +2746,17 @@ class Parser $this->seek($s); + // 2n+1 + 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]); + continue; + } + } + + $this->seek($s); + // attribute selector if ($char === '[' && $this->matchChar('[') && @@ -2489,7 +2781,7 @@ class Parser continue; } - if ($this->keyword($name)) { + if ($this->restrictedKeyword($name)) { $parts[] = $name; continue; } @@ -2555,10 +2847,31 @@ class Parser return false; } + /** + * Parse a keyword that should not start with a number + * + * @param string $word + * @param boolean $eatWhitespace + * + * @return boolean + */ + protected function restrictedKeyword(&$word, $eatWhitespace = null) + { + $s = $this->count; + + if ($this->keyword($word, $eatWhitespace) && (ord($word[0]) > 57 || ord($word[0]) < 48)) { + return true; + } + + $this->seek($s); + + return false; + } + /** * Parse a placeholder * - * @param string $placeholder + * @param string|array $placeholder * * @return boolean */ @@ -2574,6 +2887,7 @@ class Parser return true; } + if ($this->interpolation($placeholder)) { return true; } @@ -2635,12 +2949,9 @@ class Parser 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; } } @@ -2658,9 +2969,8 @@ class Parser protected function stripOptionalFlag(&$selectors) { $optional = false; - $selector = end($selectors); - $part = end($selector); + $part = end($selector); if ($part === ['!optional']) { array_pop($selectors[count($selectors) - 1]); @@ -2704,6 +3014,8 @@ class Parser $validChars = $allowNewline ? '.' : "[^\n]"; } + $m = null; + if (! $this->match('(' . $validChars . '*?)' . $this->pregQuote($what), $m, ! $until)) { return false; } @@ -2803,9 +3115,10 @@ class Parser return; } - $iniDirective = 'mbstring' . '.func_overload'; // deprecated in PHP 7.2 + // deprecated in PHP 7.2 + $iniDirective = 'mbstring.func_overload'; - if (ini_get($iniDirective) & 2) { + if (extension_loaded('mbstring') && ini_get($iniDirective) & 2) { $this->encoding = mb_internal_encoding(); mb_internal_encoding('iso-8859-1'); @@ -2817,7 +3130,7 @@ class Parser */ private function restoreEncoding() { - if ($this->encoding) { + if (extension_loaded('mbstring') && $this->encoding) { mb_internal_encoding($this->encoding); } } diff --git a/lib/scssphp/scssphp/src/SourceMap/Base64VLQ.php b/lib/scssphp/scssphp/src/SourceMap/Base64VLQ.php index d6f6452b5..61c1d30e4 100644 --- a/lib/scssphp/scssphp/src/SourceMap/Base64VLQ.php +++ b/lib/scssphp/scssphp/src/SourceMap/Base64VLQ.php @@ -130,8 +130,17 @@ class Base64VLQ private static function fromVLQSigned($value) { $negate = ($value & 1) === 1; - $value = $value >> 1; + $value = ($value >> 1) & ~(1<<(8 * PHP_INT_SIZE - 1)); // unsigned right shift - return $negate ? -$value : $value; + 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/lib/scssphp/scssphp/src/SourceMap/Base64VLQEncoder.php b/lib/scssphp/scssphp/src/SourceMap/Base64VLQEncoder.php deleted file mode 100644 index 365b4d930..000000000 --- a/lib/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/lib/scssphp/scssphp/src/Version.php b/lib/scssphp/scssphp/src/Version.php index 56c7165ef..db3e7a3b6 100644 --- a/lib/scssphp/scssphp/src/Version.php +++ b/lib/scssphp/scssphp/src/Version.php @@ -18,5 +18,5 @@ namespace ScssPhp\ScssPhp; */ class Version { - const VERSION = 'v1.0.0'; + const VERSION = 'v1.0.6'; }