diff --git a/YOUR_TEMPLATE/less/less.php b/YOUR_TEMPLATE/less/less.php index cb897f9..866aaba 100644 --- a/YOUR_TEMPLATE/less/less.php +++ b/YOUR_TEMPLATE/less/less.php @@ -16,16 +16,17 @@ * =============================================================== * Файл: less.php * --------------------------------------------------------------- - * Версия: 2.1.0 (18.07.2013) + * Версия: 2.1.2 (30.12.2013) * =============================================================== * * Использование: * --------------------------------------------------------------- * Где нибудь в начале header.php прописать: - + * - * По умолчанию подключается файл template_styles.less текущего шаблона сайта. - * туда же записывается одноимённый css-файл (который и используется в bitrix). + * По умолчанию подключается файл /res/less/template_styles.less + * а css файл кладётся в папку /res/css/ - это сделано для удобства использования автолоадера (о нём будет сказанно в следующем году). + * прис этом желательно удалить пустой template_styles.css из папки с шаблоном. * Все настройки чуть ниже. * =============================================================== */ @@ -41,9 +42,9 @@ $lessLogFile = 'less-log'; // Имя лог-файла. Файл является html-страницей и записывается в корень сайта. // Определяем входящий и выходящий файлы и определяем сжимать или нет выходящий файл. -$inputFile = $_SERVER['DOCUMENT_ROOT'].SITE_TEMPLATE_PATH."/special.less"; // Файл template_styles.less, лежащий в текущем шаблоне сайта -$outputFile = str_ireplace('.less', '.css', $inputFile); // Файл template_styles.css - который подключается к шаблону -$normal = true; // true для отключения сжатия выходящего файла. +$inputFile = $_SERVER['DOCUMENT_ROOT'].'/res/less/template_styles.less'; // Файл template_styles.less, лежащий в текущем шаблоне сайта +$outputFile = str_ireplace('less', 'css', $inputFile); // Файл template_styles.css - который подключается к шаблону +$normal = false; // true для отключения сжатия выходящего файла. $alertError = true; // false для показа ошибок компиляции вверху страницы (по умолчанию показываются js-алертом); $copyText = '@author: Павел Белоусов (www.info-expert.ru)'; // Текст, который будет записан в начало файла CSS вместе со статистикой @@ -213,7 +214,7 @@ function autoCompileLess($inpFile, $outFile, $nocompress = false, $copy) { // Добавляем копирайты и информацию по файлам в начало. $copy = ' -/* ========================================================================== +/*! ========================================================================= @outputFile: '.basename($outFile).' @inputFiles: '.implode(', ',$sourceFiles).' @date: '.date('Y-m-d H:i:s').' @@ -228,4 +229,4 @@ function autoCompileLess($inpFile, $outFile, $nocompress = false, $copy) { } } -?> +?> \ No newline at end of file diff --git a/YOUR_TEMPLATE/less/lessphp.class.php b/YOUR_TEMPLATE/less/lessphp.class.php index 447fe44..597d43b 100644 --- a/YOUR_TEMPLATE/less/lessphp.class.php +++ b/YOUR_TEMPLATE/less/lessphp.class.php @@ -1,18 +1,18 @@ + * Copyright 2013, Leaf Corcoran * Licensed under MIT or GPLv3, see LICENSE */ /** - * The less compiler and parser. + * The LESS compiler and parser. * * Converting LESS to CSS is a three stage process. The incoming file is parsed * by `lessc_parser` into a syntax tree, then it is compiled into another tree @@ -27,7 +27,7 @@ * * In summary: * - * The `lessc` class creates an intstance of the parser, feeds it LESS code, + * The `lessc` class creates an instance of the parser, feeds it LESS code, * then transforms the resulting tree to a CSS tree. This class also holds the * evaluation context, such as all available mixins and variables at any given * time. @@ -38,9 +38,10 @@ * handling things like indentation. */ class lessc { - static public $VERSION = "v0.3.9"; - static protected $TRUE = array("keyword", "true"); - static protected $FALSE = array("keyword", "false"); + static public $VERSION = "v0.4.0"; + + static public $TRUE = array("keyword", "true"); + static public $FALSE = array("keyword", "false"); protected $libFunctions = array(); protected $registeredVars = array(); @@ -55,13 +56,13 @@ class lessc { protected $numberPrecision = null; + protected $allParsedFiles = array(); + // set to the parser that generated the current line when compiling // so we know how to create error messages protected $sourceParser = null; protected $sourceLoc = null; - static public $defaultValue = array("keyword", ""); - static protected $nextImportId = 0; // uniquely identify imports // attempts to find the path of an import url, returns null for css files @@ -103,12 +104,17 @@ protected function tryImport($importPath, $parentBlock, $out) { if (substr_compare($url, '.css', -4, 4) === 0) return false; $realPath = $this->findImport($url); + if ($realPath === null) return false; if ($this->importDisabled) { return array(false, "/* import disabled */"); } + if (isset($this->allParsedFiles[realpath($realPath)])) { + return array(false, null); + } + $this->addParsedFile($realPath); $parser = $this->makeParser($realPath); $root = $parser->parse(file_get_contents($realPath)); @@ -200,7 +206,7 @@ protected function compileBlock($block) { $this->compileNestedBlock($block, array($name)); break; default: - $this->throwError("unknown block type: $block->type\n"); + $block->parser->throwError("unknown block type: $block->type\n", $block->count); } } @@ -276,32 +282,68 @@ protected function compileProps($block, $out) { foreach ($this->sortProps($block->props) as $prop) { $this->compileProp($prop, $block, $out); } + $out->lines = $this->deduplicate($out->lines); + } + + /** + * Deduplicate lines in a block. Comments are not deduplicated. If a + * duplicate rule is detected, the comments immediately preceding each + * occurence are consolidated. + */ + protected function deduplicate($lines) { + $unique = array(); + $comments = array(); + + foreach($lines as $line) { + if (strpos($line, '/*') === 0) { + $comments[] = $line; + continue; + } + if (!in_array($line, $unique)) { + $unique[] = $line; + } + array_splice($unique, array_search($line, $unique), 0, $comments); + $comments = array(); + } + return array_merge($unique, $comments); } protected function sortProps($props, $split = false) { $vars = array(); $imports = array(); $other = array(); + $stack = array(); foreach ($props as $prop) { switch ($prop[0]) { + case "comment": + $stack[] = $prop; + break; case "assign": + $stack[] = $prop; if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) { - $vars[] = $prop; + $vars = array_merge($vars, $stack); } else { - $other[] = $prop; + $other = array_merge($other, $stack); } + $stack = array(); break; case "import": $id = self::$nextImportId++; $prop[] = $id; - $imports[] = $prop; + $stack[] = $prop; + $imports = array_merge($imports, $stack); $other[] = array("import_mixin", $id); + $stack = array(); break; default: - $other[] = $prop; + $stack[] = $prop; + $other = array_merge($other, $stack); + $stack = array(); + break; } } + $other = array_merge($other, $stack); if ($split) { return array(array_merge($vars, $imports), $other); @@ -450,7 +492,7 @@ protected function eq($left, $right) { return $left == $right; } - protected function patternMatch($block, $callingArgs) { + protected function patternMatch($block, $orderedArgs, $keywordArgs) { // match the guards if it has them // any one of the groups must have all its guards pass for a match if (!empty($block->guards)) { @@ -458,7 +500,7 @@ protected function patternMatch($block, $callingArgs) { foreach ($block->guards as $guardGroup) { foreach ($guardGroup as $guard) { $this->pushEnv(); - $this->zipSetArgs($block->args, $callingArgs); + $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs); $negate = false; if ($guard[0] == "negate") { @@ -487,24 +529,34 @@ protected function patternMatch($block, $callingArgs) { } } - $numCalling = count($callingArgs); - if (empty($block->args)) { - return $block->isVararg || $numCalling == 0; + return $block->isVararg || empty($orderedArgs) && empty($keywordArgs); + } + + $remainingArgs = $block->args; + if ($keywordArgs) { + $remainingArgs = array(); + foreach ($block->args as $arg) { + if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) { + continue; + } + + $remainingArgs[] = $arg; + } } $i = -1; // no args // try to match by arity or by argument literal - foreach ($block->args as $i => $arg) { + foreach ($remainingArgs as $i => $arg) { switch ($arg[0]) { case "lit": - if (empty($callingArgs[$i]) || !$this->eq($arg[1], $callingArgs[$i])) { + if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) { return false; } break; case "arg": // no arg and no default value - if (!isset($callingArgs[$i]) && !isset($arg[2])) { + if (!isset($orderedArgs[$i]) && !isset($arg[2])) { return false; } break; @@ -519,14 +571,19 @@ protected function patternMatch($block, $callingArgs) { } else { $numMatched = $i + 1; // greater than becuase default values always match - return $numMatched >= $numCalling; + return $numMatched >= count($orderedArgs); } } - protected function patternMatchAll($blocks, $callingArgs) { + protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) { $matches = null; foreach ($blocks as $block) { - if ($this->patternMatch($block, $callingArgs)) { + // skip seen blocks that don't have arguments + if (isset($skip[$block->id]) && !isset($block->args)) { + continue; + } + + if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) { $matches[] = $block; } } @@ -535,7 +592,7 @@ protected function patternMatchAll($blocks, $callingArgs) { } // attempt to find blocks matched by path and args - protected function findBlocks($searchIn, $path, $args, $seen=array()) { + protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) { if ($searchIn == null) return null; if (isset($seen[$searchIn->id])) return null; $seen[$searchIn->id] = true; @@ -545,7 +602,7 @@ protected function findBlocks($searchIn, $path, $args, $seen=array()) { if (isset($searchIn->children[$name])) { $blocks = $searchIn->children[$name]; if (count($path) == 1) { - $matches = $this->patternMatchAll($blocks, $args); + $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen); if (!empty($matches)) { // This will return all blocks that match in the closest // scope that has any matching block, like lessjs @@ -555,7 +612,7 @@ protected function findBlocks($searchIn, $path, $args, $seen=array()) { $matches = array(); foreach ($blocks as $subBlock) { $subMatches = $this->findBlocks($subBlock, - array_slice($path, 1), $args, $seen); + array_slice($path, 1), $orderedArgs, $keywordArgs, $seen); if (!is_null($subMatches)) { foreach ($subMatches as $sm) { @@ -567,39 +624,51 @@ protected function findBlocks($searchIn, $path, $args, $seen=array()) { return count($matches) > 0 ? $matches : null; } } - if ($searchIn->parent === $searchIn) return null; - return $this->findBlocks($searchIn->parent, $path, $args, $seen); + return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen); } // sets all argument names in $args to either the default value // or the one passed in through $values - protected function zipSetArgs($args, $values) { - $i = 0; + protected function zipSetArgs($args, $orderedValues, $keywordValues) { $assignedValues = array(); - foreach ($args as $a) { + + $i = 0; + foreach ($args as $a) { if ($a[0] == "arg") { - if ($i < count($values) && !is_null($values[$i])) { - $value = $values[$i]; + if (isset($keywordValues[$a[1]])) { + // has keyword arg + $value = $keywordValues[$a[1]]; + } elseif (isset($orderedValues[$i])) { + // has ordered arg + $value = $orderedValues[$i]; + $i++; } elseif (isset($a[2])) { + // has default value $value = $a[2]; - } else $value = null; + } else { + $this->throwError("Failed to assign arg " . $a[1]); + $value = null; // :( + } $value = $this->reduce($value); $this->set($a[1], $value); $assignedValues[] = $value; + } else { + // a lit + $i++; } - $i++; } // check for a rest $last = end($args); if ($last[0] == "rest") { - $rest = array_slice($values, count($args) - 1); + $rest = array_slice($orderedValues, count($args) - 1); $this->set($last[1], $this->reduce(array("list", " ", $rest))); } - $this->env->arguments = $assignedValues; + // wow is this the only true use of PHP's + operator for arrays? + $this->env->arguments = $assignedValues + $orderedValues; } // compile a prop and update $lines or $blocks appropriately @@ -624,15 +693,38 @@ protected function compileProp($prop, $block, $out) { case 'mixin': list(, $path, $args, $suffix) = $prop; - $args = array_map(array($this, "reduce"), (array)$args); - $mixins = $this->findBlocks($block, $path, $args); + $orderedArgs = array(); + $keywordArgs = array(); + foreach ((array)$args as $arg) { + $argval = null; + switch ($arg[0]) { + case "arg": + if (!isset($arg[2])) { + $orderedArgs[] = $this->reduce(array("variable", $arg[1])); + } else { + $keywordArgs[$arg[1]] = $this->reduce($arg[2]); + } + break; + + case "lit": + $orderedArgs[] = $this->reduce($arg[1]); + break; + default: + $this->throwError("Unknown arg type: " . $arg[0]); + } + } + + $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs); if ($mixins === null) { - // fwrite(STDERR,"failed to find block: ".implode(" > ", $path)."\n"); - break; // throw error here?? + $block->parser->throwError("{$prop[1][0]} is undefined", $block->count); } foreach ($mixins as $mixin) { + if ($mixin === $block && !$orderedArgs) { + continue; + } + $haveScope = false; if (isset($mixin->parent->scope)) { $haveScope = true; @@ -644,7 +736,7 @@ protected function compileProp($prop, $block, $out) { if (isset($mixin->args)) { $haveArgs = true; $this->pushEnv(); - $this->zipSetArgs($mixin->args, $args); + $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs); } $oldParent = $mixin->parent; @@ -701,7 +793,9 @@ protected function compileProp($prop, $block, $out) { list(,$importId) = $prop; $import = $this->env->imports[$importId]; if ($import[0] === false) { - $out->lines[] = $import[1]; + if (isset($import[1])) { + $out->lines[] = $import[1]; + } } else { list(, $bottom, $parser, $importDir) = $import; $this->compileImportedProps($bottom, $block, $out, $parser, $importDir); @@ -709,7 +803,7 @@ protected function compileProp($prop, $block, $out) { break; default: - $this->throwError("unknown op: {$prop[0]}\n"); + $block->parser->throwError("unknown op: {$prop[0]}\n", $block->count); } } @@ -789,6 +883,60 @@ protected function compileValue($value) { } } + protected function lib_pow($args) { + list($base, $exp) = $this->assertArgs($args, 2, "pow"); + return pow($this->assertNumber($base), $this->assertNumber($exp)); + } + + protected function lib_pi() { + return pi(); + } + + protected function lib_mod($args) { + list($a, $b) = $this->assertArgs($args, 2, "mod"); + return $this->assertNumber($a) % $this->assertNumber($b); + } + + protected function lib_tan($num) { + return tan($this->assertNumber($num)); + } + + protected function lib_sin($num) { + return sin($this->assertNumber($num)); + } + + protected function lib_cos($num) { + return cos($this->assertNumber($num)); + } + + protected function lib_atan($num) { + $num = atan($this->assertNumber($num)); + return array("number", $num, "rad"); + } + + protected function lib_asin($num) { + $num = asin($this->assertNumber($num)); + return array("number", $num, "rad"); + } + + protected function lib_acos($num) { + $num = acos($this->assertNumber($num)); + return array("number", $num, "rad"); + } + + protected function lib_sqrt($num) { + return sqrt($this->assertNumber($num)); + } + + protected function lib_extract($value) { + list($list, $idx) = $this->assertArgs($value, 2, "extract"); + $idx = $this->assertNumber($idx); + // 1 indexed + if ($list[0] == "list" && isset($list[2][$idx - 1])) { + return $list[2][$idx - 1]; + } + } + protected function lib_isnumber($value) { return $this->toBool($value[0] == "number"); } @@ -835,6 +983,39 @@ protected function lib_argb($color){ return $this->lib_rgbahex($color); } + /** + * Given an url, decide whether to output a regular link or the base64-encoded contents of the file + * + * @param array $value either an argument list (two strings) or a single string + * @return string formatted url(), either as a link or base64-encoded + */ + protected function lib_data_uri($value) { + $mime = ($value[0] === 'list') ? $value[2][0][2] : null; + $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0]; + + $fullpath = $this->findImport($url); + + if($fullpath && ($fsize = filesize($fullpath)) !== false) { + // IE8 can't handle data uris larger than 32KB + if($fsize/1024 < 32) { + if(is_null($mime)) { + if(class_exists('finfo')) { // php 5.3+ + $finfo = new finfo(FILEINFO_MIME); + $mime = explode('; ', $finfo->file($fullpath)); + $mime = $mime[0]; + } elseif(function_exists('mime_content_type')) { // PHP 5.2 + $mime = mime_content_type($fullpath); + } + } + + if(!is_null($mime)) // fallback if the mime type is still unknown + $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath))); + } + } + + return 'url("'.$url.'")'; + } + // utility func to unquote a string protected function lib_e($arg) { switch ($arg[0]) { @@ -843,7 +1024,7 @@ protected function lib_e($arg) { if (isset($items[0])) { return $this->lib_e($items[0]); } - return self::$defaultValue; + $this->throwError("unrecognised input"); case "string": $arg[1] = ""; return $arg; @@ -893,8 +1074,14 @@ protected function lib_ceil($arg) { } protected function lib_round($arg) { - $value = $this->assertNumber($arg); - return array("number", round($value), $arg[2]); + if($arg[0] != "list") { + $value = $this->assertNumber($arg); + return array("number", round($value), $arg[2]); + } else { + $value = $this->assertNumber($arg[2][0]); + $precision = $this->assertNumber($arg[2][1]); + return array("number", round($value, $precision), $arg[2][0][2]); + } } protected function lib_unit($arg) { @@ -911,7 +1098,7 @@ protected function lib_unit($arg) { * Helper function to get arguments for color manipulation functions. * takes a list that contains a color like thing and a percentage */ - protected function colorArgs($args) { + public function colorArgs($args) { if ($args[0] != 'list' || count($args[2]) < 2) { return array(array('color', 0, 0, 0), 0); } @@ -1013,19 +1200,24 @@ protected function lib_percentage($arg) { } // mixes two colors by weight - // mix(@color1, @color2, @weight); + // mix(@color1, @color2, [@weight: 50%]); // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method protected function lib_mix($args) { - if ($args[0] != "list" || count($args[2]) < 3) + if ($args[0] != "list" || count($args[2]) < 2) $this->throwError("mix expects (color1, color2, weight)"); - list($first, $second, $weight) = $args[2]; + list($first, $second) = $args[2]; $first = $this->assertColor($first); $second = $this->assertColor($second); $first_a = $this->lib_alpha($first); $second_a = $this->lib_alpha($second); - $weight = $weight[1] / 100.0; + + if (isset($args[2][2])) { + $weight = $args[2][2][1] / 100.0; + } else { + $weight = 0.5; + } $w = $weight * 2 - 1; $a = $first_a - $second_a; @@ -1047,35 +1239,74 @@ protected function lib_mix($args) { } protected function lib_contrast($args) { - if ($args[0] != 'list' || count($args[2]) < 3) { - return array(array('color', 0, 0, 0), 0); - } + $darkColor = array('color', 0, 0, 0); + $lightColor = array('color', 255, 255, 255); + $threshold = 0.43; - list($inputColor, $darkColor, $lightColor) = $args[2]; + if ( $args[0] == 'list' ) { + $inputColor = ( isset($args[2][0]) ) ? $this->assertColor($args[2][0]) : $lightColor; + $darkColor = ( isset($args[2][1]) ) ? $this->assertColor($args[2][1]) : $darkColor; + $lightColor = ( isset($args[2][2]) ) ? $this->assertColor($args[2][2]) : $lightColor; + $threshold = ( isset($args[2][3]) ) ? $this->assertNumber($args[2][3]) : $threshold; + } + else { + $inputColor = $this->assertColor($args); + } - $inputColor = $this->assertColor($inputColor); - $darkColor = $this->assertColor($darkColor); - $lightColor = $this->assertColor($lightColor); - $hsl = $this->toHSL($inputColor); + $inputColor = $this->coerceColor($inputColor); + $darkColor = $this->coerceColor($darkColor); + $lightColor = $this->coerceColor($lightColor); - if ($hsl[3] > 50) { - return $darkColor; - } + //Figure out which is actually light and dark! + if ( $this->lib_luma($darkColor) > $this->lib_luma($lightColor) ) { + $t = $lightColor; + $lightColor = $darkColor; + $darkColor = $t; + } + + $inputColor_alpha = $this->lib_alpha($inputColor); + if ( ( $this->lib_luma($inputColor) * $inputColor_alpha) < $threshold) { + return $lightColor; + } + return $darkColor; + } - return $lightColor; + protected function lib_luma($color) { + $color = $this->coerceColor($color); + return (0.2126 * $color[0] / 255) + (0.7152 * $color[1] / 255) + (0.0722 * $color[2] / 255); } - protected function assertColor($value, $error = "expected color value") { + + public function assertColor($value, $error = "expected color value") { $color = $this->coerceColor($value); if (is_null($color)) $this->throwError($error); return $color; } - protected function assertNumber($value, $error = "expecting number") { + public function assertNumber($value, $error = "expecting number") { if ($value[0] == "number") return $value[1]; $this->throwError($error); } + public function assertArgs($value, $expectedArgs, $name="") { + if ($expectedArgs == 1) { + return $value; + } else { + if ($value[0] !== "list" || $value[1] != ",") $this->throwError("expecting list"); + $values = $value[2]; + $numValues = count($values); + if ($expectedArgs != $numValues) { + if ($name) { + $name = $name . ": "; + } + + $this->throwError("${name}expecting $expectedArgs arguments, got $numValues"); + } + + return $values; + } + } + protected function toHSL($color) { if ($color[0] == 'hsl') return $color; @@ -1220,6 +1451,10 @@ protected function reduce($value, $forExpression = false) { $var = $this->compileValue($reduced); $res = $this->reduce(array("variable", $this->vPrefix . $var)); + if ($res[0] == "raw_color") { + $res = $this->coerceColor($res); + } + if (empty($value[2])) $res = $this->lib_e($res); return $res; @@ -1237,7 +1472,7 @@ protected function reduce($value, $forExpression = false) { } $seen[$key] = true; - $out = $this->reduce($this->get($key, self::$defaultValue)); + $out = $this->reduce($this->get($key)); $seen[$key] = false; return $out; case "list": @@ -1265,8 +1500,9 @@ protected function reduce($value, $forExpression = false) { list(, $name, $args) = $value; if ($name == "%") $name = "_sprintf"; + $f = isset($this->libFunctions[$name]) ? - $this->libFunctions[$name] : array($this, 'lib_'.$name); + $this->libFunctions[$name] : array($this, 'lib_'.str_replace('-', '_', $name)); if (is_callable($f)) { if ($args[0] == 'list') @@ -1373,7 +1609,7 @@ protected function flattenList($value) { return $value; } - protected function toBool($a) { + public function toBool($a) { if ($a) return self::$TRUE; else return self::$FALSE; } @@ -1596,7 +1832,7 @@ protected function set($name, $value) { // get the highest occurrence entry for a name - protected function get($name, $default=null) { + protected function get($name) { $current = $this->env; $isArguments = $name == $this->vPrefix . 'arguments'; @@ -1613,7 +1849,7 @@ protected function get($name, $default=null) { } } - return $default; + $this->throwError("variable $name is undefined"); } // inject array of unparsed strings into environment as variables @@ -1681,7 +1917,6 @@ public function compileFile($fname, $outFname = null) { $this->importDir = (array)$this->importDir; $this->importDir[] = $pi['dirname'].'/'; - $this->allParsedFiles = array(); $this->addParsedFile($fname); $out = $this->compile(file_get_contents($fname), $fname); @@ -1850,14 +2085,14 @@ public function allParsedFiles() { return $this->allParsedFiles; } - protected function addParsedFile($file) { + public function addParsedFile($file) { $this->allParsedFiles[realpath($file)] = filemtime($file); } /** * Uses the current value of $this->count to show line and line number */ - protected function throwError($msg = null) { + public function throwError($msg = null) { if ($this->sourceLoc >= 0) { $this->sourceParser->throwError($msg, $this->sourceLoc); } @@ -2123,14 +2358,13 @@ public function parse($buffer) { $this->whitespace(); // parse the entire file - $lastCount = $this->count; while (false !== $this->parseChunk()); if ($this->count != strlen($this->buffer)) $this->throwError(); // TODO report where the block was opened - if (!is_null($this->env->parent)) + if ( !property_exists($this->env, 'parent') || !is_null($this->env->parent) ) throw new exception('parse error: unclosed block'); return $this->env; @@ -2176,6 +2410,10 @@ protected function parseChunk() { if (empty($this->buffer)) return false; $s = $this->seek(); + if ($this->whitespace()) { + return true; + } + // setting a property if ($this->keyword($key) && $this->assign() && $this->propertyValue($value, $key) && $this->end()) @@ -2256,7 +2494,7 @@ protected function parseChunk() { } // opening a simple block - if ($this->tags($tags) && $this->literal('{')) { + if ($this->tags($tags) && $this->literal('{', false)) { $tags = $this->fixTags($tags); $this->pushBlock($tags); return true; @@ -2304,7 +2542,7 @@ protected function parseChunk() { // mixin if ($this->mixinTags($tags) && - ($this->argumentValues($argv) || true) && + ($this->argumentDef($argv, $isVararg) || true) && ($this->keyword($suffix) || true) && $this->end()) { $tags = $this->fixTags($tags); @@ -2531,7 +2769,6 @@ protected function value(&$value) { // an import statement protected function import(&$out) { - $s = $this->seek(); if (!$this->literal('@import')) return false; // @import "something.css" media; @@ -2772,38 +3009,18 @@ protected function color(&$out) { return false; } - // consume a list of property values delimited by ; and wrapped in () - protected function argumentValues(&$args, $delim = ',') { - $s = $this->seek(); - if (!$this->literal('(')) return false; - - $values = array(); - while (true) { - if ($this->expressionList($value)) $values[] = $value; - if (!$this->literal($delim)) break; - else { - if ($value == null) $values[] = null; - $value = null; - } - } - - if (!$this->literal(')')) { - $this->seek($s); - return false; - } - - $args = $values; - return true; - } - // consume an argument definition list surrounded by () // each argument is a variable name with optional value // or at the end a ... or a variable named followed by ... - protected function argumentDef(&$args, &$isVararg, $delim = ',') { + // arguments are separated by , unless a ; is in the list, then ; is the + // delimiter. + protected function argumentDef(&$args, &$isVararg) { $s = $this->seek(); if (!$this->literal('(')) return false; $values = array(); + $delim = ","; + $method = "expressionList"; $isVararg = false; while (true) { @@ -2812,28 +3029,77 @@ protected function argumentDef(&$args, &$isVararg, $delim = ',') { break; } - if ($this->variable($vname)) { - $arg = array("arg", $vname); - $ss = $this->seek(); - if ($this->assign() && $this->expressionList($value)) { - $arg[] = $value; - } else { - $this->seek($ss); - if ($this->literal("...")) { - $arg[0] = "rest"; - $isVararg = true; + if ($this->$method($value)) { + if ($value[0] == "variable") { + $arg = array("arg", $value[1]); + $ss = $this->seek(); + + if ($this->assign() && $this->$method($rhs)) { + $arg[] = $rhs; + } else { + $this->seek($ss); + if ($this->literal("...")) { + $arg[0] = "rest"; + $isVararg = true; + } } + + $values[] = $arg; + if ($isVararg) break; + continue; + } else { + $values[] = array("lit", $value); } - $values[] = $arg; - if ($isVararg) break; - continue; } - if ($this->value($literal)) { - $values[] = array("lit", $literal); - } - if (!$this->literal($delim)) break; + if (!$this->literal($delim)) { + if ($delim == "," && $this->literal(";")) { + // found new delim, convert existing args + $delim = ";"; + $method = "propertyValue"; + + // transform arg list + if (isset($values[1])) { // 2 items + $newList = array(); + foreach ($values as $i => $arg) { + switch($arg[0]) { + case "arg": + if ($i) { + $this->throwError("Cannot mix ; and , as delimiter types"); + } + $newList[] = $arg[2]; + break; + case "lit": + $newList[] = $arg[1]; + break; + case "rest": + $this->throwError("Unexpected rest before semicolon"); + } + } + + $newList = array("list", ", ", $newList); + + switch ($values[0][0]) { + case "arg": + $newArg = array("arg", $values[0][1], $newList); + break; + case "lit": + $newArg = array("lit", $newList); + break; + } + + } elseif ($values) { // 1 item + $newArg = $values[0]; + } + + if ($newArg) { + $values = array($newArg); + } + } else { + break; + } + } } if (!$this->literal(')')) { @@ -2862,7 +3128,6 @@ protected function tags(&$tags, $simple = false, $delim = ',') { // list of tags of specifying mixin path // optionally separated by > (lazy, accepts extra >) protected function mixinTags(&$tags) { - $s = $this->seek(); $tags = array(); while ($this->tag($tt, true)) { $tags[] = $tt; @@ -2875,32 +3140,69 @@ protected function mixinTags(&$tags) { } // a bracketed value (contained within in a tag definition) - protected function tagBracket(&$value) { + protected function tagBracket(&$parts, &$hasExpression) { // speed shortcut if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") { return false; } $s = $this->seek(); - if ($this->literal('[') && $this->to(']', $c, true) && $this->literal(']', false)) { - $value = '['.$c.']'; - // whitespace? - if ($this->whitespace()) $value .= " "; - // escape parent selector, (yuck) - $value = str_replace($this->lessc->parentSelector, "$&$", $value); - return true; - } + $hasInterpolation = false; - $this->seek($s); - return false; - } + if ($this->literal("[", false)) { + $attrParts = array("["); + // keyword, string, operator + while (true) { + if ($this->literal("]", false)) { + $this->count--; + break; // get out early + } - protected function tagExpression(&$value) { - $s = $this->seek(); - if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) { - $value = array('exp', $exp); - return true; + if ($this->match('\s+', $m)) { + $attrParts[] = " "; + continue; + } + if ($this->string($str)) { + // escape parent selector, (yuck) + foreach ($str[2] as &$chunk) { + $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk); + } + + $attrParts[] = $str; + $hasInterpolation = true; + continue; + } + + if ($this->keyword($word)) { + $attrParts[] = $word; + continue; + } + + if ($this->interpolation($inter, false)) { + $attrParts[] = $inter; + $hasInterpolation = true; + continue; + } + + // operator, handles attr namespace too + if ($this->match('[|-~\$\*\^=]+', $m)) { + $attrParts[] = $m[0]; + continue; + } + + break; + } + + if ($this->literal("]", false)) { + $attrParts[] = "]"; + foreach ($attrParts as $part) { + $parts[] = $part; + } + $hasExpression = $hasExpression || $hasInterpolation; + return true; + } + $this->seek($s); } $this->seek($s); @@ -2916,13 +3218,9 @@ protected function tag(&$tag, $simple = false) { $s = $this->seek(); - if (!$simple && $this->tagExpression($tag)) { - return true; - } - $hasExpression = false; $parts = array(); - while ($this->tagBracket($first)) $parts[] = $first; + while ($this->tagBracket($parts, $hasExpression)); $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; @@ -2932,9 +3230,7 @@ protected function tag(&$tag, $simple = false) { $parts[] = $m[1]; if ($simple) break; - while ($this->tagBracket($brack)) { - $parts[] = $brack; - } + while ($this->tagBracket($parts, $hasExpression)); continue; } @@ -3059,7 +3355,7 @@ protected function keyword(&$word) { // consume an end of statement delimiter protected function end() { - if ($this->literal(';')) { + if ($this->literal(';', false)) { return true; } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') { // if there is end of file or a closing block next then we don't need a ; @@ -3208,9 +3504,9 @@ protected function whitespace() { if ($this->writeComments) { $gotWhite = false; while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) { - if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { + if (isset($m[1]) && empty($this->seenComments[$this->count])) { $this->append(array("comment", $m[1])); - $this->commentsSeen[$this->count] = true; + $this->seenComments[$this->count] = true; } $this->count += strlen($m[0]); $gotWhite = true; @@ -3273,6 +3569,14 @@ protected function pushBlock($selectors=null, $type=null) { $b->props = array(); $b->children = array(); + // add a reference to the parser so + // we can access the parser to throw errors + // or retrieve the sourceName of this block. + $b->parser = $this; + + // so we know the position of this block + $b->count = $this->count; + $this->env = $b; return $b; } @@ -3325,7 +3629,7 @@ protected function removeComments($text) { break; case '"': case "'": - if (preg_match('/'.$min[0].'.*?'.$min[0].'/', $text, $m, 0, $count)) + if (preg_match('/'.$min[0].'.*?(?