4 * lessphp v0.4.0@6e8e724fc7
5 * http://leafo.net/lessphp
7 * LESS css compiler, adapted from http://lesscss.org
9 * For ease of distribution, lessphp 0.4.0 is under a dual license.
10 * You are free to pick which one suits your needs.
14 * Copyright 2013, Leaf Corcoran <leafot@gmail.com>
16 * Permission is hereby granted, free of charge, to any person obtaining
17 * a copy of this software and associated documentation files (the
18 * "Software"), to deal in the Software without restriction, including
19 * without limitation the rights to use, copy, modify, merge, publish,
20 * distribute, sublicense, and/or sell copies of the Software, and to
21 * permit persons to whom the Software is furnished to do so, subject to
22 * the following conditions:
24 * The above copyright notice and this permission notice shall be
25 * included in all copies or substantial portions of the Software.
27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 * Please refer to http://www.gnu.org/licenses/gpl-3.0.html for the full
38 * text of the GPL version 3
43 * The less compiler and parser.
45 * Converting LESS to CSS is a three stage process. The incoming file is parsed
46 * by `lessc_parser` into a syntax tree, then it is compiled into another tree
47 * representing the CSS structure by `lessc`. The CSS tree is fed into a
48 * formatter, like `lessc_formatter` which then outputs CSS as a string.
50 * During the first compile, all values are *reduced*, which means that their
51 * types are brought to the lowest form before being dump as strings. This
52 * handles math equations, variable dereferences, and the like.
54 * The `parse` function of `lessc` is the entry point.
58 * The `lessc` class creates an instance of the parser, feeds it LESS code,
59 * then transforms the resulting tree to a CSS tree. This class also holds the
60 * evaluation context, such as all available mixins and variables at any given
63 * The `lessc_parser` class is only concerned with parsing its input.
65 * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
66 * handling things like indentation.
69 static public $VERSION = "v0.4.0";
70 static protected $TRUE = array("keyword", "true");
71 static protected $FALSE = array("keyword", "false");
73 protected $libFunctions = array();
74 protected $registeredVars = array();
75 protected $preserveComments = false;
77 public $vPrefix = '@'; // prefix of abstract properties
78 public $mPrefix = '$'; // prefix of abstract blocks
79 public $parentSelector = '&';
81 public $importDisabled = false;
82 public $importDir = '';
84 protected $numberPrecision = null;
86 protected $allParsedFiles = array();
88 // set to the parser that generated the current line when compiling
89 // so we know how to create error messages
90 protected $sourceParser = null;
91 protected $sourceLoc = null;
93 static protected $nextImportId = 0; // uniquely identify imports
95 // attempts to find the path of an import url, returns null for css files
96 protected function findImport($url) {
97 foreach ((array)$this->importDir
as $dir) {
98 $full = $dir.(substr($dir, -1) != '/' ?
'/' : '').$url;
99 if ($this->fileExists($file = $full.'.less') ||
$this->fileExists($file = $full)) {
107 protected function fileExists($name) {
108 return is_file($name);
111 static public function compressList($items, $delim) {
112 if (!isset($items[1]) && isset($items[0])) return $items[0];
113 else return array('list', $delim, $items);
116 static public function preg_quote($what) {
117 return preg_quote($what, '/');
120 protected function tryImport($importPath, $parentBlock, $out) {
121 if ($importPath[0] == "function" && $importPath[1] == "url") {
122 $importPath = $this->flattenList($importPath[2]);
125 $str = $this->coerceString($importPath);
126 if ($str === null) return false;
128 $url = $this->compileValue($this->lib_e($str));
130 // don't import if it ends in css
131 if (substr_compare($url, '.css', -4, 4) === 0) return false;
133 $realPath = $this->findImport($url);
135 if ($realPath === null) return false;
137 if ($this->importDisabled
) {
138 return array(false, "/* import disabled */");
141 if (isset($this->allParsedFiles
[realpath($realPath)])) {
142 return array(false, null);
145 $this->addParsedFile($realPath);
146 $parser = $this->makeParser($realPath);
147 $root = $parser->parse(file_get_contents($realPath));
149 // set the parents of all the block props
150 foreach ($root->props
as $prop) {
151 if ($prop[0] == "block") {
152 $prop[1]->parent
= $parentBlock;
156 // copy mixins into scope, set their parents
157 // bring blocks from import into current block
158 // TODO: need to mark the source parser these came from this file
159 foreach ($root->children
as $childName => $child) {
160 if (isset($parentBlock->children
[$childName])) {
161 $parentBlock->children
[$childName] = array_merge(
162 $parentBlock->children
[$childName],
165 $parentBlock->children
[$childName] = $child;
169 $pi = pathinfo($realPath);
170 $dir = $pi["dirname"];
172 list($top, $bottom) = $this->sortProps($root->props
, true);
173 $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
175 return array(true, $bottom, $parser, $dir);
178 protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
179 $oldSourceParser = $this->sourceParser
;
181 $oldImport = $this->importDir
;
183 // TODO: this is because the importDir api is stupid
184 $this->importDir
= (array)$this->importDir
;
185 array_unshift($this->importDir
, $importDir);
187 foreach ($props as $prop) {
188 $this->compileProp($prop, $block, $out);
191 $this->importDir
= $oldImport;
192 $this->sourceParser
= $oldSourceParser;
196 * Recursively compiles a block.
198 * A block is analogous to a CSS block in most cases. A single LESS document
199 * is encapsulated in a block when parsed, but it does not have parent tags
200 * so all of it's children appear on the root level when compiled.
202 * Blocks are made up of props and children.
204 * Props are property instructions, array tuples which describe an action
205 * to be taken, eg. write a property, set a variable, mixin a block.
207 * The children of a block are just all the blocks that are defined within.
208 * This is used to look up mixins when performing a mixin.
210 * Compiling the block involves pushing a fresh environment on the stack,
211 * and iterating through the props, compiling each one.
213 * See lessc::compileProp()
216 protected function compileBlock($block) {
217 switch ($block->type
) {
219 $this->compileRoot($block);
222 $this->compileCSSBlock($block);
225 $this->compileMedia($block);
228 $name = "@" . $block->name
;
229 if (!empty($block->value
)) {
230 $name .= " " . $this->compileValue($this->reduce($block->value
));
233 $this->compileNestedBlock($block, array($name));
236 $this->throwError("unknown block type: $block->type\n");
240 protected function compileCSSBlock($block) {
241 $env = $this->pushEnv();
243 $selectors = $this->compileSelectors($block->tags
);
244 $env->selectors
= $this->multiplySelectors($selectors);
245 $out = $this->makeOutputBlock(null, $env->selectors
);
247 $this->scope
->children
[] = $out;
248 $this->compileProps($block, $out);
250 $block->scope
= $env; // mixins carry scope with them!
254 protected function compileMedia($media) {
255 $env = $this->pushEnv($media);
256 $parentScope = $this->mediaParent($this->scope
);
258 $query = $this->compileMediaQuery($this->multiplyMedia($env));
260 $this->scope
= $this->makeOutputBlock($media->type
, array($query));
261 $parentScope->children
[] = $this->scope
;
263 $this->compileProps($media, $this->scope
);
265 if (count($this->scope
->lines
) > 0) {
266 $orphanSelelectors = $this->findClosestSelectors();
267 if (!is_null($orphanSelelectors)) {
268 $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
269 $orphan->lines
= $this->scope
->lines
;
270 array_unshift($this->scope
->children
, $orphan);
271 $this->scope
->lines
= array();
275 $this->scope
= $this->scope
->parent
;
279 protected function mediaParent($scope) {
280 while (!empty($scope->parent
)) {
281 if (!empty($scope->type
) && $scope->type
!= "media") {
284 $scope = $scope->parent
;
290 protected function compileNestedBlock($block, $selectors) {
291 $this->pushEnv($block);
292 $this->scope
= $this->makeOutputBlock($block->type
, $selectors);
293 $this->scope
->parent
->children
[] = $this->scope
;
295 $this->compileProps($block, $this->scope
);
297 $this->scope
= $this->scope
->parent
;
301 protected function compileRoot($root) {
303 $this->scope
= $this->makeOutputBlock($root->type
);
304 $this->compileProps($root, $this->scope
);
308 protected function compileProps($block, $out) {
309 foreach ($this->sortProps($block->props
) as $prop) {
310 $this->compileProp($prop, $block, $out);
313 $out->lines
= array_values(array_unique($out->lines
));
316 protected function sortProps($props, $split = false) {
321 foreach ($props as $prop) {
324 if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix
) {
331 $id = self
::$nextImportId++
;
334 $other[] = array("import_mixin", $id);
342 return array(array_merge($vars, $imports), $other);
344 return array_merge($vars, $imports, $other);
348 protected function compileMediaQuery($queries) {
349 $compiledQueries = array();
350 foreach ($queries as $query) {
352 foreach ($query as $q) {
355 $parts[] = implode(" ", array_slice($q, 1));
359 $parts[] = "($q[1]: " .
360 $this->compileValue($this->reduce($q[2])) . ")";
362 $parts[] = "($q[1])";
366 $parts[] = $this->compileValue($this->reduce($q));
371 if (count($parts) > 0) {
372 $compiledQueries[] = implode(" and ", $parts);
377 if (!empty($parts)) {
379 implode($this->formatter
->selectorSeparator
, $compiledQueries);
384 protected function multiplyMedia($env, $childQueries = null) {
386 !empty($env->block
->type
) && $env->block
->type
!= "media")
388 return $childQueries;
391 // plain old block, skip
392 if (empty($env->block
->type
)) {
393 return $this->multiplyMedia($env->parent
, $childQueries);
397 $queries = $env->block
->queries
;
398 if (is_null($childQueries)) {
401 foreach ($queries as $parent) {
402 foreach ($childQueries as $child) {
403 $out[] = array_merge($parent, $child);
408 return $this->multiplyMedia($env->parent
, $out);
411 protected function expandParentSelectors(&$tag, $replace) {
412 $parts = explode("$&$", $tag);
414 foreach ($parts as &$part) {
415 $part = str_replace($this->parentSelector
, $replace, $part, $c);
418 $tag = implode($this->parentSelector
, $parts);
422 protected function findClosestSelectors() {
425 while ($env !== null) {
426 if (isset($env->selectors
)) {
427 $selectors = $env->selectors
;
437 // multiply $selectors against the nearest selectors in env
438 protected function multiplySelectors($selectors) {
439 // find parent selectors
441 $parentSelectors = $this->findClosestSelectors();
442 if (is_null($parentSelectors)) {
443 // kill parent reference in top level selector
444 foreach ($selectors as &$s) {
445 $this->expandParentSelectors($s, "");
452 foreach ($parentSelectors as $parent) {
453 foreach ($selectors as $child) {
454 $count = $this->expandParentSelectors($child, $parent);
456 // don't prepend the parent tag if & was used
458 $out[] = trim($child);
460 $out[] = trim($parent . ' ' . $child);
468 // reduces selector expressions
469 protected function compileSelectors($selectors) {
472 foreach ($selectors as $s) {
475 $out[] = trim($this->compileValue($this->reduce($value)));
484 protected function eq($left, $right) {
485 return $left == $right;
488 protected function patternMatch($block, $orderedArgs, $keywordArgs) {
489 // match the guards if it has them
490 // any one of the groups must have all its guards pass for a match
491 if (!empty($block->guards
)) {
492 $groupPassed = false;
493 foreach ($block->guards
as $guardGroup) {
494 foreach ($guardGroup as $guard) {
496 $this->zipSetArgs($block->args
, $orderedArgs, $keywordArgs);
499 if ($guard[0] == "negate") {
504 $passed = $this->reduce($guard) == self
::$TRUE;
505 if ($negate) $passed = !$passed;
512 $groupPassed = false;
517 if ($groupPassed) break;
525 if (empty($block->args
)) {
526 return $block->isVararg ||
empty($orderedArgs) && empty($keywordArgs);
529 $remainingArgs = $block->args
;
531 $remainingArgs = array();
532 foreach ($block->args
as $arg) {
533 if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
537 $remainingArgs[] = $arg;
542 // try to match by arity or by argument literal
543 foreach ($remainingArgs as $i => $arg) {
546 if (empty($orderedArgs[$i]) ||
!$this->eq($arg[1], $orderedArgs[$i])) {
551 // no arg and no default value
552 if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
557 $i--; // rest can be empty
562 if ($block->isVararg
) {
563 return true; // not having enough is handled above
565 $numMatched = $i +
1;
566 // greater than becuase default values always match
567 return $numMatched >= count($orderedArgs);
571 protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) {
573 foreach ($blocks as $block) {
574 // skip seen blocks that don't have arguments
575 if (isset($skip[$block->id
]) && !isset($block->args
)) {
579 if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
587 // attempt to find blocks matched by path and args
588 protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) {
589 if ($searchIn == null) return null;
590 if (isset($seen[$searchIn->id
])) return null;
591 $seen[$searchIn->id
] = true;
595 if (isset($searchIn->children
[$name])) {
596 $blocks = $searchIn->children
[$name];
597 if (count($path) == 1) {
598 $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
599 if (!empty($matches)) {
600 // This will return all blocks that match in the closest
601 // scope that has any matching block, like lessjs
606 foreach ($blocks as $subBlock) {
607 $subMatches = $this->findBlocks($subBlock,
608 array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
610 if (!is_null($subMatches)) {
611 foreach ($subMatches as $sm) {
617 return count($matches) > 0 ?
$matches : null;
620 if ($searchIn->parent
=== $searchIn) return null;
621 return $this->findBlocks($searchIn->parent
, $path, $orderedArgs, $keywordArgs, $seen);
624 // sets all argument names in $args to either the default value
625 // or the one passed in through $values
626 protected function zipSetArgs($args, $orderedValues, $keywordValues) {
627 $assignedValues = array();
630 foreach ($args as $a) {
631 if ($a[0] == "arg") {
632 if (isset($keywordValues[$a[1]])) {
634 $value = $keywordValues[$a[1]];
635 } elseif (isset($orderedValues[$i])) {
637 $value = $orderedValues[$i];
639 } elseif (isset($a[2])) {
643 $this->throwError("Failed to assign arg " . $a[1]);
647 $value = $this->reduce($value);
648 $this->set($a[1], $value);
649 $assignedValues[] = $value;
658 if ($last[0] == "rest") {
659 $rest = array_slice($orderedValues, count($args) - 1);
660 $this->set($last[1], $this->reduce(array("list", " ", $rest)));
663 // wow is this the only true use of PHP's + operator for arrays?
664 $this->env
->arguments
= $assignedValues +
$orderedValues;
667 // compile a prop and update $lines or $blocks appropriately
668 protected function compileProp($prop, $block, $out) {
669 // set error position context
670 $this->sourceLoc
= isset($prop[-1]) ?
$prop[-1] : -1;
674 list(, $name, $value) = $prop;
675 if ($name[0] == $this->vPrefix
) {
676 $this->set($name, $value);
678 $out->lines
[] = $this->formatter
->property($name,
679 $this->compileValue($this->reduce($value)));
683 list(, $child) = $prop;
684 $this->compileBlock($child);
687 list(, $path, $args, $suffix) = $prop;
689 $orderedArgs = array();
690 $keywordArgs = array();
691 foreach ((array)$args as $arg) {
695 if (!isset($arg[2])) {
696 $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
698 $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
703 $orderedArgs[] = $this->reduce($arg[1]);
706 $this->throwError("Unknown arg type: " . $arg[0]);
710 $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
712 if ($mixins === null) {
713 $this->throwError("{$prop[1][0]} is undefined");
716 foreach ($mixins as $mixin) {
717 if ($mixin === $block && !$orderedArgs) {
722 if (isset($mixin->parent
->scope
)) {
724 $mixinParentEnv = $this->pushEnv();
725 $mixinParentEnv->storeParent
= $mixin->parent
->scope
;
729 if (isset($mixin->args
)) {
732 $this->zipSetArgs($mixin->args
, $orderedArgs, $keywordArgs);
735 $oldParent = $mixin->parent
;
736 if ($mixin != $block) $mixin->parent
= $block;
738 foreach ($this->sortProps($mixin->props
) as $subProp) {
739 if ($suffix !== null &&
740 $subProp[0] == "assign" &&
741 is_string($subProp[1]) &&
742 $subProp[1]{0} != $this->vPrefix
)
746 array($subProp[2], array('keyword', $suffix))
750 $this->compileProp($subProp, $mixin, $out);
753 $mixin->parent
= $oldParent;
755 if ($haveArgs) $this->popEnv();
756 if ($haveScope) $this->popEnv();
761 $out->lines
[] = $prop[1];
764 list(, $name, $value) = $prop;
765 $out->lines
[] = "@$name " . $this->compileValue($this->reduce($value)).';';
768 $out->lines
[] = $prop[1];
771 list(, $importPath, $importId) = $prop;
772 $importPath = $this->reduce($importPath);
774 if (!isset($this->env
->imports
)) {
775 $this->env
->imports
= array();
778 $result = $this->tryImport($importPath, $block, $out);
780 $this->env
->imports
[$importId] = $result === false ?
781 array(false, "@import " . $this->compileValue($importPath).";") :
786 list(,$importId) = $prop;
787 $import = $this->env
->imports
[$importId];
788 if ($import[0] === false) {
789 if (isset($import[1])) {
790 $out->lines
[] = $import[1];
793 list(, $bottom, $parser, $importDir) = $import;
794 $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
799 $this->throwError("unknown op: {$prop[0]}\n");
805 * Compiles a primitive value into a CSS property value.
807 * Values in lessphp are typed by being wrapped in arrays, their format is
810 * array(type, contents [, additional_contents]*)
812 * The input is expected to be reduced. This function will not work on
813 * things like expressions and variables.
815 protected function compileValue($value) {
819 // [2] - array of values
820 return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
822 if (!empty($this->formatter
->compressColors
)) {
823 return $this->compileValue($this->coerceColor($value));
830 list(, $num, $unit) = $value;
833 if ($this->numberPrecision
!== null) {
834 $num = round($num, $this->numberPrecision
);
838 // [1] - contents of string (includes quotes)
839 list(, $delim, $content) = $value;
840 foreach ($content as &$part) {
841 if (is_array($part)) {
842 $part = $this->compileValue($part);
845 return $delim . implode($content) . $delim;
847 // [1] - red component (either number or a %)
848 // [2] - green component
849 // [3] - blue component
850 // [4] - optional alpha component
851 list(, $r, $g, $b) = $value;
856 if (count($value) == 5 && $value[4] != 1) { // rgba
857 return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
860 $h = sprintf("#%02x%02x%02x", $r, $g, $b);
862 if (!empty($this->formatter
->compressColors
)) {
863 // Converting hex color to short notation (e.g. #003399 to #039)
864 if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
865 $h = '#' . $h[1] . $h[3] . $h[5];
872 list(, $name, $args) = $value;
873 return $name.'('.$this->compileValue($args).')';
874 default: // assumed to be unit
875 $this->throwError("unknown value type: $value[0]");
879 protected function lib_pow($args) {
880 list($base, $exp) = $this->assertArgs($args, 2, "pow");
881 return pow($this->assertNumber($base), $this->assertNumber($exp));
884 protected function lib_pi() {
888 protected function lib_mod($args) {
889 list($a, $b) = $this->assertArgs($args, 2, "mod");
890 return $this->assertNumber($a) %
$this->assertNumber($b);
893 protected function lib_tan($num) {
894 return tan($this->assertNumber($num));
897 protected function lib_sin($num) {
898 return sin($this->assertNumber($num));
901 protected function lib_cos($num) {
902 return cos($this->assertNumber($num));
905 protected function lib_atan($num) {
906 $num = atan($this->assertNumber($num));
907 return array("number", $num, "rad");
910 protected function lib_asin($num) {
911 $num = asin($this->assertNumber($num));
912 return array("number", $num, "rad");
915 protected function lib_acos($num) {
916 $num = acos($this->assertNumber($num));
917 return array("number", $num, "rad");
920 protected function lib_sqrt($num) {
921 return sqrt($this->assertNumber($num));
924 protected function lib_extract($value) {
925 list($list, $idx) = $this->assertArgs($value, 2, "extract");
926 $idx = $this->assertNumber($idx);
928 if ($list[0] == "list" && isset($list[2][$idx - 1])) {
929 return $list[2][$idx - 1];
933 protected function lib_isnumber($value) {
934 return $this->toBool($value[0] == "number");
937 protected function lib_isstring($value) {
938 return $this->toBool($value[0] == "string");
941 protected function lib_iscolor($value) {
942 return $this->toBool($this->coerceColor($value));
945 protected function lib_iskeyword($value) {
946 return $this->toBool($value[0] == "keyword");
949 protected function lib_ispixel($value) {
950 return $this->toBool($value[0] == "number" && $value[2] == "px");
953 protected function lib_ispercentage($value) {
954 return $this->toBool($value[0] == "number" && $value[2] == "%");
957 protected function lib_isem($value) {
958 return $this->toBool($value[0] == "number" && $value[2] == "em");
961 protected function lib_isrem($value) {
962 return $this->toBool($value[0] == "number" && $value[2] == "rem");
965 protected function lib_rgbahex($color) {
966 $color = $this->coerceColor($color);
968 $this->throwError("color expected for rgbahex");
970 return sprintf("#%02x%02x%02x%02x",
971 isset($color[4]) ?
$color[4]*255 : 255,
972 $color[1],$color[2], $color[3]);
975 protected function lib_argb($color){
976 return $this->lib_rgbahex($color);
979 // utility func to unquote a string
980 protected function lib_e($arg) {
984 if (isset($items[0])) {
985 return $this->lib_e($items[0]);
987 $this->throwError("unrecognised input");
994 return array("keyword", $this->compileValue($arg));
998 protected function lib__sprintf($args) {
999 if ($args[0] != "list") return $args;
1001 $string = array_shift($values);
1002 $template = $this->compileValue($this->lib_e($string));
1005 if (preg_match_all('/%[dsa]/', $template, $m)) {
1006 foreach ($m[0] as $match) {
1007 $val = isset($values[$i]) ?
1008 $this->reduce($values[$i]) : array('keyword', '');
1010 // lessjs compat, renders fully expanded color, not raw color
1011 if ($color = $this->coerceColor($val)) {
1016 $rep = $this->compileValue($this->lib_e($val));
1017 $template = preg_replace('/'.self
::preg_quote($match).'/',
1018 $rep, $template, 1);
1022 $d = $string[0] == "string" ?
$string[1] : '"';
1023 return array("string", $d, array($template));
1026 protected function lib_floor($arg) {
1027 $value = $this->assertNumber($arg);
1028 return array("number", floor($value), $arg[2]);
1031 protected function lib_ceil($arg) {
1032 $value = $this->assertNumber($arg);
1033 return array("number", ceil($value), $arg[2]);
1036 protected function lib_round($arg) {
1037 if($arg[0] != "list") {
1038 $value = $this->assertNumber($arg);
1039 return array("number", round($value), $arg[2]);
1041 $value = $this->assertNumber($arg[2][0]);
1042 $precision = $this->assertNumber($arg[2][1]);
1043 return array("number", round($value, $precision), $arg[2][0][2]);
1047 protected function lib_unit($arg) {
1048 if ($arg[0] == "list") {
1049 list($number, $newUnit) = $arg[2];
1050 return array("number", $this->assertNumber($number),
1051 $this->compileValue($this->lib_e($newUnit)));
1053 return array("number", $this->assertNumber($arg), "");
1058 * Helper function to get arguments for color manipulation functions.
1059 * takes a list that contains a color like thing and a percentage
1061 protected function colorArgs($args) {
1062 if ($args[0] != 'list' ||
count($args[2]) < 2) {
1063 return array(array('color', 0, 0, 0), 0);
1065 list($color, $delta) = $args[2];
1066 $color = $this->assertColor($color);
1067 $delta = floatval($delta[1]);
1069 return array($color, $delta);
1072 protected function lib_darken($args) {
1073 list($color, $delta) = $this->colorArgs($args);
1075 $hsl = $this->toHSL($color);
1076 $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
1077 return $this->toRGB($hsl);
1080 protected function lib_lighten($args) {
1081 list($color, $delta) = $this->colorArgs($args);
1083 $hsl = $this->toHSL($color);
1084 $hsl[3] = $this->clamp($hsl[3] +
$delta, 100);
1085 return $this->toRGB($hsl);
1088 protected function lib_saturate($args) {
1089 list($color, $delta) = $this->colorArgs($args);
1091 $hsl = $this->toHSL($color);
1092 $hsl[2] = $this->clamp($hsl[2] +
$delta, 100);
1093 return $this->toRGB($hsl);
1096 protected function lib_desaturate($args) {
1097 list($color, $delta) = $this->colorArgs($args);
1099 $hsl = $this->toHSL($color);
1100 $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
1101 return $this->toRGB($hsl);
1104 protected function lib_spin($args) {
1105 list($color, $delta) = $this->colorArgs($args);
1107 $hsl = $this->toHSL($color);
1109 $hsl[1] = $hsl[1] +
$delta %
360;
1110 if ($hsl[1] < 0) $hsl[1] +
= 360;
1112 return $this->toRGB($hsl);
1115 protected function lib_fadeout($args) {
1116 list($color, $delta) = $this->colorArgs($args);
1117 $color[4] = $this->clamp((isset($color[4]) ?
$color[4] : 1) - $delta/100);
1121 protected function lib_fadein($args) {
1122 list($color, $delta) = $this->colorArgs($args);
1123 $color[4] = $this->clamp((isset($color[4]) ?
$color[4] : 1) +
$delta/100);
1127 protected function lib_hue($color) {
1128 $hsl = $this->toHSL($this->assertColor($color));
1129 return round($hsl[1]);
1132 protected function lib_saturation($color) {
1133 $hsl = $this->toHSL($this->assertColor($color));
1134 return round($hsl[2]);
1137 protected function lib_lightness($color) {
1138 $hsl = $this->toHSL($this->assertColor($color));
1139 return round($hsl[3]);
1142 // get the alpha of a color
1143 // defaults to 1 for non-colors or colors without an alpha
1144 protected function lib_alpha($value) {
1145 if (!is_null($color = $this->coerceColor($value))) {
1146 return isset($color[4]) ?
$color[4] : 1;
1150 // set the alpha of the color
1151 protected function lib_fade($args) {
1152 list($color, $alpha) = $this->colorArgs($args);
1153 $color[4] = $this->clamp($alpha / 100.0);
1157 protected function lib_percentage($arg) {
1158 $num = $this->assertNumber($arg);
1159 return array("number", $num*100, "%");
1162 // mixes two colors by weight
1163 // mix(@color1, @color2, [@weight: 50%]);
1164 // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
1165 protected function lib_mix($args) {
1166 if ($args[0] != "list" ||
count($args[2]) < 2)
1167 $this->throwError("mix expects (color1, color2, weight)");
1169 list($first, $second) = $args[2];
1170 $first = $this->assertColor($first);
1171 $second = $this->assertColor($second);
1173 $first_a = $this->lib_alpha($first);
1174 $second_a = $this->lib_alpha($second);
1176 if (isset($args[2][2])) {
1177 $weight = $args[2][2][1] / 100.0;
1182 $w = $weight * 2 - 1;
1183 $a = $first_a - $second_a;
1185 $w1 = (($w * $a == -1 ?
$w : ($w +
$a)/(1 +
$w * $a)) +
1) / 2.0;
1188 $new = array('color',
1189 $w1 * $first[1] +
$w2 * $second[1],
1190 $w1 * $first[2] +
$w2 * $second[2],
1191 $w1 * $first[3] +
$w2 * $second[3],
1194 if ($first_a != 1.0 ||
$second_a != 1.0) {
1195 $new[] = $first_a * $weight +
$second_a * ($weight - 1);
1198 return $this->fixColor($new);
1201 protected function lib_contrast($args) {
1202 if ($args[0] != 'list' ||
count($args[2]) < 3) {
1203 return array(array('color', 0, 0, 0), 0);
1206 list($inputColor, $darkColor, $lightColor) = $args[2];
1208 $inputColor = $this->assertColor($inputColor);
1209 $darkColor = $this->assertColor($darkColor);
1210 $lightColor = $this->assertColor($lightColor);
1211 $hsl = $this->toHSL($inputColor);
1220 protected function assertColor($value, $error = "expected color value") {
1221 $color = $this->coerceColor($value);
1222 if (is_null($color)) $this->throwError($error);
1226 protected function assertNumber($value, $error = "expecting number") {
1227 if ($value[0] == "number") return $value[1];
1228 $this->throwError($error);
1231 protected function assertArgs($value, $expectedArgs, $name="") {
1232 if ($expectedArgs == 1) {
1235 if ($value[0] !== "list" ||
$value[1] != ",") $this->throwError("expecting list");
1236 $values = $value[2];
1237 $numValues = count($values);
1238 if ($expectedArgs != $numValues) {
1240 $name = $name . ": ";
1243 $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
1250 protected function toHSL($color) {
1251 if ($color[0] == 'hsl') return $color;
1253 $r = $color[1] / 255;
1254 $g = $color[2] / 255;
1255 $b = $color[3] / 255;
1257 $min = min($r, $g, $b);
1258 $max = max($r, $g, $b);
1260 $L = ($min +
$max) / 2;
1265 $S = ($max - $min)/($max +
$min);
1267 $S = ($max - $min)/(2.0 - $max - $min);
1269 if ($r == $max) $H = ($g - $b)/($max - $min);
1270 elseif ($g == $max) $H = 2.0 +
($b - $r)/($max - $min);
1271 elseif ($b == $max) $H = 4.0 +
($r - $g)/($max - $min);
1276 ($H < 0 ?
$H +
6 : $H)*60,
1281 if (count($color) > 4) $out[] = $color[4]; // copy alpha
1285 protected function toRGB_helper($comp, $temp1, $temp2) {
1286 if ($comp < 0) $comp +
= 1.0;
1287 elseif ($comp > 1) $comp -= 1.0;
1289 if (6 * $comp < 1) return $temp1 +
($temp2 - $temp1) * 6 * $comp;
1290 if (2 * $comp < 1) return $temp2;
1291 if (3 * $comp < 2) return $temp1 +
($temp2 - $temp1)*((2/3) - $comp) * 6;
1297 * Converts a hsl array into a color value in rgb.
1298 * Expects H to be in range of 0 to 360, S and L in 0 to 100
1300 protected function toRGB($color) {
1301 if ($color[0] == 'color') return $color;
1303 $H = $color[1] / 360;
1304 $S = $color[2] / 100;
1305 $L = $color[3] / 100;
1314 $temp1 = 2.0 * $L - $temp2;
1316 $r = $this->toRGB_helper($H +
1/3, $temp1, $temp2);
1317 $g = $this->toRGB_helper($H, $temp1, $temp2);
1318 $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
1321 // $out = array('color', round($r*255), round($g*255), round($b*255));
1322 $out = array('color', $r*255, $g*255, $b*255);
1323 if (count($color) > 4) $out[] = $color[4]; // copy alpha
1327 protected function clamp($v, $max = 1, $min = 0) {
1328 return min($max, max($min, $v));
1332 * Convert the rgb, rgba, hsl color literals of function type
1333 * as returned by the parser into values of color type.
1335 protected function funcToColor($func) {
1337 if ($func[2][0] != 'list') return false; // need a list of arguments
1338 $rawComponents = $func[2][2];
1340 if ($fname == 'hsl' ||
$fname == 'hsla') {
1341 $hsl = array('hsl');
1343 foreach ($rawComponents as $c) {
1344 $val = $this->reduce($c);
1345 $val = isset($val[1]) ?
floatval($val[1]) : 0;
1347 if ($i == 0) $clamp = 360;
1348 elseif ($i < 3) $clamp = 100;
1351 $hsl[] = $this->clamp($val, $clamp);
1355 while (count($hsl) < 4) $hsl[] = 0;
1356 return $this->toRGB($hsl);
1358 } elseif ($fname == 'rgb' ||
$fname == 'rgba') {
1359 $components = array();
1361 foreach ($rawComponents as $c) {
1362 $c = $this->reduce($c);
1364 if ($c[0] == "number" && $c[2] == "%") {
1365 $components[] = 255 * ($c[1] / 100);
1367 $components[] = floatval($c[1]);
1369 } elseif ($i == 4) {
1370 if ($c[0] == "number" && $c[2] == "%") {
1371 $components[] = 1.0 * ($c[1] / 100);
1373 $components[] = floatval($c[1]);
1379 while (count($components) < 3) $components[] = 0;
1380 array_unshift($components, 'color');
1381 return $this->fixColor($components);
1387 protected function reduce($value, $forExpression = false) {
1388 switch ($value[0]) {
1390 $reduced = $this->reduce($value[1]);
1391 $var = $this->compileValue($reduced);
1392 $res = $this->reduce(array("variable", $this->vPrefix
. $var));
1394 if ($res[0] == "raw_color") {
1395 $res = $this->coerceColor($res);
1398 if (empty($value[2])) $res = $this->lib_e($res);
1403 if (is_array($key)) {
1404 $key = $this->reduce($key);
1405 $key = $this->vPrefix
. $this->compileValue($this->lib_e($key));
1408 $seen =& $this->env
->seenNames
;
1410 if (!empty($seen[$key])) {
1411 $this->throwError("infinite loop detected: $key");
1415 $out = $this->reduce($this->get($key));
1416 $seen[$key] = false;
1419 foreach ($value[2] as &$item) {
1420 $item = $this->reduce($item, $forExpression);
1424 return $this->evaluate($value);
1426 foreach ($value[2] as &$part) {
1427 if (is_array($part)) {
1428 $strip = $part[0] == "variable";
1429 $part = $this->reduce($part);
1430 if ($strip) $part = $this->lib_e($part);
1435 list(,$inner) = $value;
1436 return $this->lib_e($this->reduce($inner));
1438 $color = $this->funcToColor($value);
1439 if ($color) return $color;
1441 list(, $name, $args) = $value;
1442 if ($name == "%") $name = "_sprintf";
1443 $f = isset($this->libFunctions
[$name]) ?
1444 $this->libFunctions
[$name] : array($this, 'lib_'.$name);
1446 if (is_callable($f)) {
1447 if ($args[0] == 'list')
1448 $args = self
::compressList($args[2], $args[1]);
1450 $ret = call_user_func($f, $this->reduce($args, true), $this);
1452 if (is_null($ret)) {
1453 return array("string", "", array(
1454 $name, "(", $args, ")"
1458 // convert to a typed value if the result is a php primitive
1459 if (is_numeric($ret)) $ret = array('number', $ret, "");
1460 elseif (!is_array($ret)) $ret = array('keyword', $ret);
1465 // plain function, reduce args
1466 $value[2] = $this->reduce($value[2]);
1469 list(, $op, $exp) = $value;
1470 $exp = $this->reduce($exp);
1472 if ($exp[0] == "number") {
1481 return array("string", "", array($op, $exp));
1484 if ($forExpression) {
1485 switch ($value[0]) {
1487 if ($color = $this->coerceColor($value)) {
1492 return $this->coerceColor($value);
1500 // coerce a value for use in color operation
1501 protected function coerceColor($value) {
1503 case 'color': return $value;
1505 $c = array("color", 0, 0, 0);
1506 $colorStr = substr($value[1], 1);
1507 $num = hexdec($colorStr);
1508 $width = strlen($colorStr) == 3 ?
16 : 256;
1510 for ($i = 3; $i > 0; $i--) { // 3 2 1
1514 $c[$i] = $t * (256/$width) +
$t * floor(16/$width);
1520 if (isset(self
::$cssColors[$name])) {
1521 $rgba = explode(',', self
::$cssColors[$name]);
1524 return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1526 return array('color', $rgba[0], $rgba[1], $rgba[2]);
1532 // make something string like into a string
1533 protected function coerceString($value) {
1534 switch ($value[0]) {
1538 return array("string", "", array($value[1]));
1543 // turn list of length 1 into value type
1544 protected function flattenList($value) {
1545 if ($value[0] == "list" && count($value[2]) == 1) {
1546 return $this->flattenList($value[2][0]);
1551 protected function toBool($a) {
1552 if ($a) return self
::$TRUE;
1553 else return self
::$FALSE;
1556 // evaluate an expression
1557 protected function evaluate($exp) {
1558 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1560 $left = $this->reduce($left, true);
1561 $right = $this->reduce($right, true);
1563 if ($leftColor = $this->coerceColor($left)) {
1567 if ($rightColor = $this->coerceColor($right)) {
1568 $right = $rightColor;
1574 // operators that work on all types
1576 return $this->toBool($left == self
::$TRUE && $right == self
::$TRUE);
1580 return $this->toBool($this->eq($left, $right) );
1583 if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1587 // type based operators
1588 $fname = "op_${ltype}_${rtype}";
1589 if (is_callable(array($this, $fname))) {
1590 $out = $this->$fname($op, $left, $right);
1591 if (!is_null($out)) return $out;
1594 // make the expression look it did before being parsed
1596 if ($whiteBefore) $paddedOp = " " . $paddedOp;
1597 if ($whiteAfter) $paddedOp .= " ";
1599 return array("string", "", array($left, $paddedOp, $right));
1602 protected function stringConcatenate($left, $right) {
1603 if ($strLeft = $this->coerceString($left)) {
1604 if ($right[0] == "string") {
1607 $strLeft[2][] = $right;
1611 if ($strRight = $this->coerceString($right)) {
1612 array_unshift($strRight[2], $left);
1618 // make sure a color's components don't go out of bounds
1619 protected function fixColor($c) {
1620 foreach (range(1, 3) as $i) {
1621 if ($c[$i] < 0) $c[$i] = 0;
1622 if ($c[$i] > 255) $c[$i] = 255;
1628 protected function op_number_color($op, $lft, $rgt) {
1629 if ($op == '+' ||
$op == '*') {
1630 return $this->op_color_number($op, $rgt, $lft);
1634 protected function op_color_number($op, $lft, $rgt) {
1635 if ($rgt[0] == '%') $rgt[1] /= 100;
1637 return $this->op_color_color($op, $lft,
1638 array_fill(1, count($lft) - 1, $rgt[1]));
1641 protected function op_color_color($op, $left, $right) {
1642 $out = array('color');
1643 $max = count($left) > count($right) ?
count($left) : count($right);
1644 foreach (range(1, $max - 1) as $i) {
1645 $lval = isset($left[$i]) ?
$left[$i] : 0;
1646 $rval = isset($right[$i]) ?
$right[$i] : 0;
1649 $out[] = $lval +
$rval;
1652 $out[] = $lval - $rval;
1655 $out[] = $lval * $rval;
1658 $out[] = $lval %
$rval;
1661 if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
1662 $out[] = $lval / $rval;
1665 $this->throwError('evaluate error: color op number failed on op '.$op);
1668 return $this->fixColor($out);
1671 function lib_red($color){
1672 $color = $this->coerceColor($color);
1673 if (is_null($color)) {
1674 $this->throwError('color expected for red()');
1680 function lib_green($color){
1681 $color = $this->coerceColor($color);
1682 if (is_null($color)) {
1683 $this->throwError('color expected for green()');
1689 function lib_blue($color){
1690 $color = $this->coerceColor($color);
1691 if (is_null($color)) {
1692 $this->throwError('color expected for blue()');
1699 // operator on two numbers
1700 protected function op_number_number($op, $left, $right) {
1701 $unit = empty($left[2]) ?
$right[2] : $left[2];
1706 $value = $left[1] +
$right[1];
1709 $value = $left[1] * $right[1];
1712 $value = $left[1] - $right[1];
1715 $value = $left[1] %
$right[1];
1718 if ($right[1] == 0) $this->throwError('parse error: divide by zero');
1719 $value = $left[1] / $right[1];
1722 return $this->toBool($left[1] < $right[1]);
1724 return $this->toBool($left[1] > $right[1]);
1726 return $this->toBool($left[1] >= $right[1]);
1728 return $this->toBool($left[1] <= $right[1]);
1730 $this->throwError('parse error: unknown number operator: '.$op);
1733 return array("number", $value, $unit);
1737 /* environment functions */
1739 protected function makeOutputBlock($type, $selectors = null) {
1741 $b->lines
= array();
1742 $b->children
= array();
1743 $b->selectors
= $selectors;
1745 $b->parent
= $this->scope
;
1749 // the state of execution
1750 protected function pushEnv($block = null) {
1752 $e->parent
= $this->env
;
1753 $e->store
= array();
1760 // pop something off the stack
1761 protected function popEnv() {
1763 $this->env
= $this->env
->parent
;
1767 // set something in the current env
1768 protected function set($name, $value) {
1769 $this->env
->store
[$name] = $value;
1773 // get the highest occurrence entry for a name
1774 protected function get($name) {
1775 $current = $this->env
;
1777 $isArguments = $name == $this->vPrefix
. 'arguments';
1779 if ($isArguments && isset($current->arguments
)) {
1780 return array('list', ' ', $current->arguments
);
1783 if (isset($current->store
[$name]))
1784 return $current->store
[$name];
1786 $current = isset($current->storeParent
) ?
1787 $current->storeParent
: $current->parent
;
1791 $this->throwError("variable $name is undefined");
1794 // inject array of unparsed strings into environment as variables
1795 protected function injectVariables($args) {
1797 $parser = new lessc_parser($this, __METHOD__
);
1798 foreach ($args as $name => $strValue) {
1799 if ($name{0} != '@') $name = '@'.$name;
1801 $parser->buffer
= (string)$strValue;
1802 if (!$parser->propertyValue($value)) {
1803 throw new Exception("failed to parse passed in variable $name: $strValue");
1806 $this->set($name, $value);
1811 * Initialize any static state, can initialize parser for a file
1812 * $opts isn't used yet
1814 public function __construct($fname = null) {
1815 if ($fname !== null) {
1816 // used for deprecated parse method
1817 $this->_parseFile
= $fname;
1821 public function compile($string, $name = null) {
1822 $locale = setlocale(LC_NUMERIC
, 0);
1823 setlocale(LC_NUMERIC
, "C");
1825 $this->parser
= $this->makeParser($name);
1826 $root = $this->parser
->parse($string);
1829 $this->scope
= null;
1831 $this->formatter
= $this->newFormatter();
1833 if (!empty($this->registeredVars
)) {
1834 $this->injectVariables($this->registeredVars
);
1837 $this->sourceParser
= $this->parser
; // used for error messages
1838 $this->compileBlock($root);
1841 $this->formatter
->block($this->scope
);
1842 $out = ob_get_clean();
1843 setlocale(LC_NUMERIC
, $locale);
1847 public function compileFile($fname, $outFname = null) {
1848 if (!is_readable($fname)) {
1849 throw new Exception('load error: failed to find '.$fname);
1852 $pi = pathinfo($fname);
1854 $oldImport = $this->importDir
;
1856 $this->importDir
= (array)$this->importDir
;
1857 $this->importDir
[] = $pi['dirname'].'/';
1859 $this->addParsedFile($fname);
1861 $out = $this->compile(file_get_contents($fname), $fname);
1863 $this->importDir
= $oldImport;
1865 if ($outFname !== null) {
1866 return file_put_contents($outFname, $out);
1872 // compile only if changed input has changed or output doesn't exist
1873 public function checkedCompile($in, $out) {
1874 if (!is_file($out) ||
filemtime($in) > filemtime($out)) {
1875 $this->compileFile($in, $out);
1882 * Execute lessphp on a .less file or a lessphp cache structure
1884 * The lessphp cache structure contains information about a specific
1885 * less file having been parsed. It can be used as a hint for future
1886 * calls to determine whether or not a rebuild is required.
1888 * The cache structure contains two important keys that may be used
1891 * compiled: The final compiled CSS
1892 * updated: The time (in seconds) the CSS was last compiled
1894 * The cache structure is a plain-ol' PHP associative array and can
1895 * be serialized and unserialized without a hitch.
1897 * @param mixed $in Input
1898 * @param bool $force Force rebuild?
1899 * @return array lessphp cache structure
1901 public function cachedCompile($in, $force = false) {
1905 if (is_string($in)) {
1907 } elseif (is_array($in) and isset($in['root'])) {
1908 if ($force or ! isset($in['files'])) {
1909 // If we are forcing a recompile or if for some reason the
1910 // structure does not contain any file information we should
1911 // specify the root to trigger a rebuild.
1912 $root = $in['root'];
1913 } elseif (isset($in['files']) and is_array($in['files'])) {
1914 foreach ($in['files'] as $fname => $ftime ) {
1915 if (!file_exists($fname) or filemtime($fname) > $ftime) {
1916 // One of the files we knew about previously has changed
1917 // so we should look at our incoming root again.
1918 $root = $in['root'];
1924 // TODO: Throw an exception? We got neither a string nor something
1925 // that looks like a compatible lessphp cache structure.
1929 if ($root !== null) {
1930 // If we have a root value which means we should rebuild.
1932 $out['root'] = $root;
1933 $out['compiled'] = $this->compileFile($root);
1934 $out['files'] = $this->allParsedFiles();
1935 $out['updated'] = time();
1938 // No changes, pass back the structure
1939 // we were given initially.
1945 // parse and compile buffer
1946 // This is deprecated
1947 public function parse($str = null, $initialVariables = null) {
1948 if (is_array($str)) {
1949 $initialVariables = $str;
1953 $oldVars = $this->registeredVars
;
1954 if ($initialVariables !== null) {
1955 $this->setVariables($initialVariables);
1959 if (empty($this->_parseFile
)) {
1960 throw new exception("nothing to parse");
1963 $out = $this->compileFile($this->_parseFile
);
1965 $out = $this->compile($str);
1968 $this->registeredVars
= $oldVars;
1972 protected function makeParser($name) {
1973 $parser = new lessc_parser($this, $name);
1974 $parser->writeComments
= $this->preserveComments
;
1979 public function setFormatter($name) {
1980 $this->formatterName
= $name;
1983 protected function newFormatter() {
1984 $className = "lessc_formatter_lessjs";
1985 if (!empty($this->formatterName
)) {
1986 if (!is_string($this->formatterName
))
1987 return $this->formatterName
;
1988 $className = "lessc_formatter_$this->formatterName";
1991 return new $className;
1994 public function setPreserveComments($preserve) {
1995 $this->preserveComments
= $preserve;
1998 public function registerFunction($name, $func) {
1999 $this->libFunctions
[$name] = $func;
2002 public function unregisterFunction($name) {
2003 unset($this->libFunctions
[$name]);
2006 public function setVariables($variables) {
2007 $this->registeredVars
= array_merge($this->registeredVars
, $variables);
2010 public function unsetVariable($name) {
2011 unset($this->registeredVars
[$name]);
2014 public function setImportDir($dirs) {
2015 $this->importDir
= (array)$dirs;
2018 public function addImportDir($dir) {
2019 $this->importDir
= (array)$this->importDir
;
2020 $this->importDir
[] = $dir;
2023 public function allParsedFiles() {
2024 return $this->allParsedFiles
;
2027 public function addParsedFile($file) {
2028 $this->allParsedFiles
[realpath($file)] = filemtime($file);
2032 * Uses the current value of $this->count to show line and line number
2034 protected function throwError($msg = null) {
2035 if ($this->sourceLoc
>= 0) {
2036 $this->sourceParser
->throwError($msg, $this->sourceLoc
);
2038 throw new exception($msg);
2041 // compile file $in to file $out if $in is newer than $out
2042 // returns true when it compiles, false otherwise
2043 public static function ccompile($in, $out, $less = null) {
2044 if ($less === null) {
2047 return $less->checkedCompile($in, $out);
2050 public static function cexecute($in, $force = false, $less = null) {
2051 if ($less === null) {
2054 return $less->cachedCompile($in, $force);
2057 static protected $cssColors = array(
2058 'aliceblue' => '240,248,255',
2059 'antiquewhite' => '250,235,215',
2060 'aqua' => '0,255,255',
2061 'aquamarine' => '127,255,212',
2062 'azure' => '240,255,255',
2063 'beige' => '245,245,220',
2064 'bisque' => '255,228,196',
2066 'blanchedalmond' => '255,235,205',
2067 'blue' => '0,0,255',
2068 'blueviolet' => '138,43,226',
2069 'brown' => '165,42,42',
2070 'burlywood' => '222,184,135',
2071 'cadetblue' => '95,158,160',
2072 'chartreuse' => '127,255,0',
2073 'chocolate' => '210,105,30',
2074 'coral' => '255,127,80',
2075 'cornflowerblue' => '100,149,237',
2076 'cornsilk' => '255,248,220',
2077 'crimson' => '220,20,60',
2078 'cyan' => '0,255,255',
2079 'darkblue' => '0,0,139',
2080 'darkcyan' => '0,139,139',
2081 'darkgoldenrod' => '184,134,11',
2082 'darkgray' => '169,169,169',
2083 'darkgreen' => '0,100,0',
2084 'darkgrey' => '169,169,169',
2085 'darkkhaki' => '189,183,107',
2086 'darkmagenta' => '139,0,139',
2087 'darkolivegreen' => '85,107,47',
2088 'darkorange' => '255,140,0',
2089 'darkorchid' => '153,50,204',
2090 'darkred' => '139,0,0',
2091 'darksalmon' => '233,150,122',
2092 'darkseagreen' => '143,188,143',
2093 'darkslateblue' => '72,61,139',
2094 'darkslategray' => '47,79,79',
2095 'darkslategrey' => '47,79,79',
2096 'darkturquoise' => '0,206,209',
2097 'darkviolet' => '148,0,211',
2098 'deeppink' => '255,20,147',
2099 'deepskyblue' => '0,191,255',
2100 'dimgray' => '105,105,105',
2101 'dimgrey' => '105,105,105',
2102 'dodgerblue' => '30,144,255',
2103 'firebrick' => '178,34,34',
2104 'floralwhite' => '255,250,240',
2105 'forestgreen' => '34,139,34',
2106 'fuchsia' => '255,0,255',
2107 'gainsboro' => '220,220,220',
2108 'ghostwhite' => '248,248,255',
2109 'gold' => '255,215,0',
2110 'goldenrod' => '218,165,32',
2111 'gray' => '128,128,128',
2112 'green' => '0,128,0',
2113 'greenyellow' => '173,255,47',
2114 'grey' => '128,128,128',
2115 'honeydew' => '240,255,240',
2116 'hotpink' => '255,105,180',
2117 'indianred' => '205,92,92',
2118 'indigo' => '75,0,130',
2119 'ivory' => '255,255,240',
2120 'khaki' => '240,230,140',
2121 'lavender' => '230,230,250',
2122 'lavenderblush' => '255,240,245',
2123 'lawngreen' => '124,252,0',
2124 'lemonchiffon' => '255,250,205',
2125 'lightblue' => '173,216,230',
2126 'lightcoral' => '240,128,128',
2127 'lightcyan' => '224,255,255',
2128 'lightgoldenrodyellow' => '250,250,210',
2129 'lightgray' => '211,211,211',
2130 'lightgreen' => '144,238,144',
2131 'lightgrey' => '211,211,211',
2132 'lightpink' => '255,182,193',
2133 'lightsalmon' => '255,160,122',
2134 'lightseagreen' => '32,178,170',
2135 'lightskyblue' => '135,206,250',
2136 'lightslategray' => '119,136,153',
2137 'lightslategrey' => '119,136,153',
2138 'lightsteelblue' => '176,196,222',
2139 'lightyellow' => '255,255,224',
2140 'lime' => '0,255,0',
2141 'limegreen' => '50,205,50',
2142 'linen' => '250,240,230',
2143 'magenta' => '255,0,255',
2144 'maroon' => '128,0,0',
2145 'mediumaquamarine' => '102,205,170',
2146 'mediumblue' => '0,0,205',
2147 'mediumorchid' => '186,85,211',
2148 'mediumpurple' => '147,112,219',
2149 'mediumseagreen' => '60,179,113',
2150 'mediumslateblue' => '123,104,238',
2151 'mediumspringgreen' => '0,250,154',
2152 'mediumturquoise' => '72,209,204',
2153 'mediumvioletred' => '199,21,133',
2154 'midnightblue' => '25,25,112',
2155 'mintcream' => '245,255,250',
2156 'mistyrose' => '255,228,225',
2157 'moccasin' => '255,228,181',
2158 'navajowhite' => '255,222,173',
2159 'navy' => '0,0,128',
2160 'oldlace' => '253,245,230',
2161 'olive' => '128,128,0',
2162 'olivedrab' => '107,142,35',
2163 'orange' => '255,165,0',
2164 'orangered' => '255,69,0',
2165 'orchid' => '218,112,214',
2166 'palegoldenrod' => '238,232,170',
2167 'palegreen' => '152,251,152',
2168 'paleturquoise' => '175,238,238',
2169 'palevioletred' => '219,112,147',
2170 'papayawhip' => '255,239,213',
2171 'peachpuff' => '255,218,185',
2172 'peru' => '205,133,63',
2173 'pink' => '255,192,203',
2174 'plum' => '221,160,221',
2175 'powderblue' => '176,224,230',
2176 'purple' => '128,0,128',
2178 'rosybrown' => '188,143,143',
2179 'royalblue' => '65,105,225',
2180 'saddlebrown' => '139,69,19',
2181 'salmon' => '250,128,114',
2182 'sandybrown' => '244,164,96',
2183 'seagreen' => '46,139,87',
2184 'seashell' => '255,245,238',
2185 'sienna' => '160,82,45',
2186 'silver' => '192,192,192',
2187 'skyblue' => '135,206,235',
2188 'slateblue' => '106,90,205',
2189 'slategray' => '112,128,144',
2190 'slategrey' => '112,128,144',
2191 'snow' => '255,250,250',
2192 'springgreen' => '0,255,127',
2193 'steelblue' => '70,130,180',
2194 'tan' => '210,180,140',
2195 'teal' => '0,128,128',
2196 'thistle' => '216,191,216',
2197 'tomato' => '255,99,71',
2198 'transparent' => '0,0,0,0',
2199 'turquoise' => '64,224,208',
2200 'violet' => '238,130,238',
2201 'wheat' => '245,222,179',
2202 'white' => '255,255,255',
2203 'whitesmoke' => '245,245,245',
2204 'yellow' => '255,255,0',
2205 'yellowgreen' => '154,205,50'
2209 // responsible for taking a string of LESS code and converting it into a
2211 class lessc_parser
{
2212 static protected $nextBlockId = 0; // used to uniquely identify blocks
2214 static protected $precedence = array(
2228 static protected $whitePattern;
2229 static protected $commentMulti;
2231 static protected $commentSingle = "//";
2232 static protected $commentMultiLeft = "/*";
2233 static protected $commentMultiRight = "*/";
2235 // regex string to match any of the operators
2236 static protected $operatorString;
2238 // these properties will supress division unless it's inside parenthases
2239 static protected $supressDivisionProps =
2240 array('/border-radius$/i', '/^font$/i');
2242 protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
2243 protected $lineDirectives = array("charset");
2246 * if we are in parens we can be more liberal with whitespace around
2247 * operators because it must evaluate to a single value and thus is less
2251 * property1: 10 -5; // is two numbers, 10 and -5
2252 * property2: (10 -5); // should evaluate to 5
2254 protected $inParens = false;
2256 // caches preg escaped literals
2257 static protected $literalCache = array();
2259 public function __construct($lessc, $sourceName = null) {
2260 $this->eatWhiteDefault
= true;
2261 // reference to less needed for vPrefix, mPrefix, and parentSelector
2262 $this->lessc
= $lessc;
2264 $this->sourceName
= $sourceName; // name used for error messages
2266 $this->writeComments
= false;
2268 if (!self
::$operatorString) {
2269 self
::$operatorString =
2270 '('.implode('|', array_map(array('lessc', 'preg_quote'),
2271 array_keys(self
::$precedence))).')';
2273 $commentSingle = lessc
::preg_quote(self
::$commentSingle);
2274 $commentMultiLeft = lessc
::preg_quote(self
::$commentMultiLeft);
2275 $commentMultiRight = lessc
::preg_quote(self
::$commentMultiRight);
2277 self
::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
2278 self
::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self
::$commentMulti.')\s*|\s+/Ais';
2282 public function parse($buffer) {
2286 $this->env
= null; // block stack
2287 $this->buffer
= $this->writeComments ?
$buffer : $this->removeComments($buffer);
2288 $this->pushSpecialBlock("root");
2289 $this->eatWhiteDefault
= true;
2290 $this->seenComments
= array();
2292 // trim whitespace on head
2293 // if (preg_match('/^\s+/', $this->buffer, $m)) {
2294 // $this->line += substr_count($m[0], "\n");
2295 // $this->buffer = ltrim($this->buffer);
2297 $this->whitespace();
2299 // parse the entire file
2300 $lastCount = $this->count
;
2301 while (false !== $this->parseChunk());
2303 if ($this->count
!= strlen($this->buffer
))
2304 $this->throwError();
2306 // TODO report where the block was opened
2307 if (!is_null($this->env
->parent
))
2308 throw new exception('parse error: unclosed block');
2314 * Parse a single chunk off the head of the buffer and append it to the
2315 * current parse environment.
2316 * Returns false when the buffer is empty, or when there is an error.
2318 * This function is called repeatedly until the entire document is
2321 * This parser is most similar to a recursive descent parser. Single
2322 * functions represent discrete grammatical rules for the language, and
2323 * they are able to capture the text that represents those rules.
2325 * Consider the function lessc::keyword(). (all parse functions are
2326 * structured the same)
2328 * The function takes a single reference argument. When calling the
2329 * function it will attempt to match a keyword on the head of the buffer.
2330 * If it is successful, it will place the keyword in the referenced
2331 * argument, advance the position in the buffer, and return true. If it
2332 * fails then it won't advance the buffer and it will return false.
2334 * All of these parse functions are powered by lessc::match(), which behaves
2335 * the same way, but takes a literal regular expression. Sometimes it is
2336 * more convenient to use match instead of creating a new function.
2338 * Because of the format of the functions, to parse an entire string of
2339 * grammatical rules, you can chain them together using &&.
2341 * But, if some of the rules in the chain succeed before one fails, then
2342 * the buffer position will be left at an invalid state. In order to
2343 * avoid this, lessc::seek() is used to remember and set buffer positions.
2345 * Before parsing a chain, use $s = $this->seek() to remember the current
2346 * position into $s. Then if a chain fails, use $this->seek($s) to
2347 * go back where we started.
2349 protected function parseChunk() {
2350 if (empty($this->buffer
)) return false;
2353 // setting a property
2354 if ($this->keyword($key) && $this->assign() &&
2355 $this->propertyValue($value, $key) && $this->end())
2357 $this->append(array('assign', $key, $value), $s);
2364 // look for special css blocks
2365 if ($this->literal('@', false)) {
2369 if ($this->literal('@media')) {
2370 if (($this->mediaQueryList($mediaQueries) ||
true)
2371 && $this->literal('{'))
2373 $media = $this->pushSpecialBlock("media");
2374 $media->queries
= is_null($mediaQueries) ?
array() : $mediaQueries;
2382 if ($this->literal("@", false) && $this->keyword($dirName)) {
2383 if ($this->isDirective($dirName, $this->blockDirectives
)) {
2384 if (($this->openString("{", $dirValue, null, array(";")) ||
true) &&
2385 $this->literal("{"))
2387 $dir = $this->pushSpecialBlock("directive");
2388 $dir->name
= $dirName;
2389 if (isset($dirValue)) $dir->value
= $dirValue;
2392 } elseif ($this->isDirective($dirName, $this->lineDirectives
)) {
2393 if ($this->propertyValue($dirValue) && $this->end()) {
2394 $this->append(array("directive", $dirName, $dirValue));
2403 // setting a variable
2404 if ($this->variable($var) && $this->assign() &&
2405 $this->propertyValue($value) && $this->end())
2407 $this->append(array('assign', $var, $value), $s);
2413 if ($this->import($importValue)) {
2414 $this->append($importValue, $s);
2418 // opening parametric mixin
2419 if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
2420 ($this->guards($guards) ||
true) &&
2421 $this->literal('{'))
2423 $block = $this->pushBlock($this->fixTags(array($tag)));
2424 $block->args
= $args;
2425 $block->isVararg
= $isVararg;
2426 if (!empty($guards)) $block->guards
= $guards;
2432 // opening a simple block
2433 if ($this->tags($tags) && $this->literal('{')) {
2434 $tags = $this->fixTags($tags);
2435 $this->pushBlock($tags);
2442 if ($this->literal('}', false)) {
2444 $block = $this->pop();
2445 } catch (exception
$e) {
2447 $this->throwError($e->getMessage());
2451 if (is_null($block->type
)) {
2453 if (!isset($block->args
)) {
2454 foreach ($block->tags
as $tag) {
2455 if (!is_string($tag) ||
$tag{0} != $this->lessc
->mPrefix
) {
2462 foreach ($block->tags
as $tag) {
2463 if (is_string($tag)) {
2464 $this->env
->children
[$tag][] = $block;
2470 $this->append(array('block', $block), $s);
2473 // this is done here so comments aren't bundled into he block that
2475 $this->whitespace();
2480 if ($this->mixinTags($tags) &&
2481 ($this->argumentDef($argv, $isVararg) ||
true) &&
2482 ($this->keyword($suffix) ||
true) && $this->end())
2484 $tags = $this->fixTags($tags);
2485 $this->append(array('mixin', $tags, $argv, $suffix), $s);
2492 if ($this->literal(';')) return true;
2494 return false; // got nothing, throw error
2497 protected function isDirective($dirname, $directives) {
2498 // TODO: cache pattern in parser
2499 $pattern = implode("|",
2500 array_map(array("lessc", "preg_quote"), $directives));
2501 $pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
2503 return preg_match($pattern, $dirname);
2506 protected function fixTags($tags) {
2507 // move @ tags out of variable namespace
2508 foreach ($tags as &$tag) {
2509 if ($tag{0} == $this->lessc
->vPrefix
)
2510 $tag[0] = $this->lessc
->mPrefix
;
2515 // a list of expressions
2516 protected function expressionList(&$exps) {
2519 while ($this->expression($exp)) {
2523 if (count($values) == 0) return false;
2525 $exps = lessc
::compressList($values, ' ');
2530 * Attempt to consume an expression.
2531 * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
2533 protected function expression(&$out) {
2534 if ($this->value($lhs)) {
2535 $out = $this->expHelper($lhs, 0);
2537 // look for / shorthand
2538 if (!empty($this->env
->supressedDivision
)) {
2539 unset($this->env
->supressedDivision
);
2541 if ($this->literal("/") && $this->value($rhs)) {
2542 $out = array("list", "",
2543 array($out, array("keyword", "/"), $rhs));
2555 * recursively parse infix equation with $lhs at precedence $minP
2557 protected function expHelper($lhs, $minP) {
2558 $this->inExp
= true;
2559 $ss = $this->seek();
2562 $whiteBefore = isset($this->buffer
[$this->count
- 1]) &&
2563 ctype_space($this->buffer
[$this->count
- 1]);
2565 // If there is whitespace before the operator, then we require
2566 // whitespace after the operator for it to be an expression
2567 $needWhite = $whiteBefore && !$this->inParens
;
2569 if ($this->match(self
::$operatorString.($needWhite ?
'\s' : ''), $m) && self
::$precedence[$m[1]] >= $minP) {
2570 if (!$this->inParens
&& isset($this->env
->currentProperty
) && $m[1] == "/" && empty($this->env
->supressedDivision
)) {
2571 foreach (self
::$supressDivisionProps as $pattern) {
2572 if (preg_match($pattern, $this->env
->currentProperty
)) {
2573 $this->env
->supressedDivision
= true;
2580 $whiteAfter = isset($this->buffer
[$this->count
- 1]) &&
2581 ctype_space($this->buffer
[$this->count
- 1]);
2583 if (!$this->value($rhs)) break;
2585 // peek for next operator to see what to do with rhs
2586 if ($this->peek(self
::$operatorString, $next) && self
::$precedence[$next[1]] > self
::$precedence[$m[1]]) {
2587 $rhs = $this->expHelper($rhs, self
::$precedence[$next[1]]);
2590 $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
2591 $ss = $this->seek();
2604 // consume a list of values for a property
2605 public function propertyValue(&$value, $keyName = null) {
2608 if ($keyName !== null) $this->env
->currentProperty
= $keyName;
2611 while ($this->expressionList($v)) {
2614 if (!$this->literal(',')) break;
2617 if ($s) $this->seek($s);
2619 if ($keyName !== null) unset($this->env
->currentProperty
);
2621 if (count($values) == 0) return false;
2623 $value = lessc
::compressList($values, ', ');
2627 protected function parenValue(&$out) {
2631 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] != "(") {
2635 $inParens = $this->inParens
;
2636 if ($this->literal("(") &&
2637 ($this->inParens
= true) && $this->expression($exp) &&
2638 $this->literal(")"))
2641 $this->inParens
= $inParens;
2644 $this->inParens
= $inParens;
2652 protected function value(&$value) {
2656 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] == "-") {
2658 if ($this->literal("-", false) &&
2659 (($this->variable($inner) && $inner = array("variable", $inner)) ||
2660 $this->unit($inner) ||
2661 $this->parenValue($inner)))
2663 $value = array("unary", "-", $inner);
2670 if ($this->parenValue($value)) return true;
2671 if ($this->unit($value)) return true;
2672 if ($this->color($value)) return true;
2673 if ($this->func($value)) return true;
2674 if ($this->string($value)) return true;
2676 if ($this->keyword($word)) {
2677 $value = array('keyword', $word);
2682 if ($this->variable($var)) {
2683 $value = array('variable', $var);
2687 // unquote string (should this work on any type?
2688 if ($this->literal("~") && $this->string($str)) {
2689 $value = array("escape", $str);
2696 if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
2697 $value = array('keyword', '\\'.$m[1]);
2706 // an import statement
2707 protected function import(&$out) {
2709 if (!$this->literal('@import')) return false;
2711 // @import "something.css" media;
2712 // @import url("something.css") media;
2713 // @import url(something.css) media;
2715 if ($this->propertyValue($value)) {
2716 $out = array("import", $value);
2721 protected function mediaQueryList(&$out) {
2722 if ($this->genericList($list, "mediaQuery", ",", false)) {
2729 protected function mediaQuery(&$out) {
2732 $expressions = null;
2735 if (($this->literal("only") && ($only = true) ||
$this->literal("not") && ($not = true) ||
true) && $this->keyword($mediaType)) {
2736 $prop = array("mediaType");
2737 if (isset($only)) $prop[] = "only";
2738 if (isset($not)) $prop[] = "not";
2739 $prop[] = $mediaType;
2746 if (!empty($mediaType) && !$this->literal("and")) {
2749 $this->genericList($expressions, "mediaExpression", "and", false);
2750 if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
2753 if (count($parts) == 0) {
2762 protected function mediaExpression(&$out) {
2765 if ($this->literal("(") &&
2766 $this->keyword($feature) &&
2767 ($this->literal(":") && $this->expression($value) ||
true) &&
2768 $this->literal(")"))
2770 $out = array("mediaExp", $feature);
2771 if ($value) $out[] = $value;
2773 } elseif ($this->variable($variable)) {
2774 $out = array('variable', $variable);
2782 // an unbounded string stopped by $end
2783 protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) {
2784 $oldWhite = $this->eatWhiteDefault
;
2785 $this->eatWhiteDefault
= false;
2787 $stop = array("'", '"', "@{", $end);
2788 $stop = array_map(array("lessc", "preg_quote"), $stop);
2789 // $stop[] = self::$commentMulti;
2791 if (!is_null($rejectStrs)) {
2792 $stop = array_merge($stop, $rejectStrs);
2795 $patt = '(.*?)('.implode("|", $stop).')';
2800 while ($this->match($patt, $m, false)) {
2801 if (!empty($m[1])) {
2804 $nestingLevel +
= substr_count($m[1], $nestingOpen);
2810 $this->count
-= strlen($tok);
2812 if ($nestingLevel == 0) {
2819 if (($tok == "'" ||
$tok == '"') && $this->string($str)) {
2824 if ($tok == "@{" && $this->interpolation($inter)) {
2825 $content[] = $inter;
2829 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
2834 $this->count+
= strlen($tok);
2837 $this->eatWhiteDefault
= $oldWhite;
2839 if (count($content) == 0) return false;
2842 if (is_string(end($content))) {
2843 $content[count($content) - 1] = rtrim(end($content));
2846 $out = array("string", "", $content);
2850 protected function string(&$out) {
2852 if ($this->literal('"', false)) {
2854 } elseif ($this->literal("'", false)) {
2862 // look for either ending delim , escape, or string interpolation
2863 $patt = '([^\n]*?)(@\{|\\\\|' .
2864 lessc
::preg_quote($delim).')';
2866 $oldWhite = $this->eatWhiteDefault
;
2867 $this->eatWhiteDefault
= false;
2869 while ($this->match($patt, $m, false)) {
2871 if ($m[2] == "@{") {
2872 $this->count
-= strlen($m[2]);
2873 if ($this->interpolation($inter, false)) {
2874 $content[] = $inter;
2876 $this->count +
= strlen($m[2]);
2877 $content[] = "@{"; // ignore it
2879 } elseif ($m[2] == '\\') {
2881 if ($this->literal($delim, false)) {
2882 $content[] = $delim;
2885 $this->count
-= strlen($delim);
2890 $this->eatWhiteDefault
= $oldWhite;
2892 if ($this->literal($delim)) {
2893 $out = array("string", $delim, $content);
2901 protected function interpolation(&$out) {
2902 $oldWhite = $this->eatWhiteDefault
;
2903 $this->eatWhiteDefault
= true;
2906 if ($this->literal("@{") &&
2907 $this->openString("}", $interp, null, array("'", '"', ";")) &&
2908 $this->literal("}", false))
2910 $out = array("interpolate", $interp);
2911 $this->eatWhiteDefault
= $oldWhite;
2912 if ($this->eatWhiteDefault
) $this->whitespace();
2916 $this->eatWhiteDefault
= $oldWhite;
2921 protected function unit(&$unit) {
2923 if (isset($this->buffer
[$this->count
])) {
2924 $char = $this->buffer
[$this->count
];
2925 if (!ctype_digit($char) && $char != ".") return false;
2928 if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
2929 $unit = array("number", $m[1], empty($m[2]) ?
"" : $m[2]);
2936 protected function color(&$out) {
2937 if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
2938 if (strlen($m[1]) > 7) {
2939 $out = array("string", "", array($m[1]));
2941 $out = array("raw_color", $m[1]);
2949 // consume an argument definition list surrounded by ()
2950 // each argument is a variable name with optional value
2951 // or at the end a ... or a variable named followed by ...
2952 // arguments are separated by , unless a ; is in the list, then ; is the
2954 protected function argumentDef(&$args, &$isVararg) {
2956 if (!$this->literal('(')) return false;
2960 $method = "expressionList";
2964 if ($this->literal("...")) {
2969 if ($this->$method($value)) {
2970 if ($value[0] == "variable") {
2971 $arg = array("arg", $value[1]);
2972 $ss = $this->seek();
2974 if ($this->assign() && $this->$method($rhs)) {
2978 if ($this->literal("...")) {
2985 if ($isVararg) break;
2988 $values[] = array("lit", $value);
2993 if (!$this->literal($delim)) {
2994 if ($delim == "," && $this->literal(";")) {
2995 // found new delim, convert existing args
2997 $method = "propertyValue";
2999 // transform arg list
3000 if (isset($values[1])) { // 2 items
3002 foreach ($values as $i => $arg) {
3006 $this->throwError("Cannot mix ; and , as delimiter types");
3008 $newList[] = $arg[2];
3011 $newList[] = $arg[1];
3014 $this->throwError("Unexpected rest before semicolon");
3018 $newList = array("list", ", ", $newList);
3020 switch ($values[0][0]) {
3022 $newArg = array("arg", $values[0][1], $newList);
3025 $newArg = array("lit", $newList);
3029 } elseif ($values) { // 1 item
3030 $newArg = $values[0];
3034 $values = array($newArg);
3042 if (!$this->literal(')')) {
3052 // consume a list of tags
3053 // this accepts a hanging delimiter
3054 protected function tags(&$tags, $simple = false, $delim = ',') {
3056 while ($this->tag($tt, $simple)) {
3058 if (!$this->literal($delim)) break;
3060 if (count($tags) == 0) return false;
3065 // list of tags of specifying mixin path
3066 // optionally separated by > (lazy, accepts extra >)
3067 protected function mixinTags(&$tags) {
3070 while ($this->tag($tt, true)) {
3072 $this->literal(">");
3075 if (count($tags) == 0) return false;
3080 // a bracketed value (contained within in a tag definition)
3081 protected function tagBracket(&$parts, &$hasExpression) {
3083 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] != "[") {
3089 $hasInterpolation = false;
3091 if ($this->literal("[", false)) {
3092 $attrParts = array("[");
3093 // keyword, string, operator
3095 if ($this->literal("]", false)) {
3097 break; // get out early
3100 if ($this->match('\s+', $m)) {
3104 if ($this->string($str)) {
3105 // escape parent selector, (yuck)
3106 foreach ($str[2] as &$chunk) {
3107 $chunk = str_replace($this->lessc
->parentSelector
, "$&$", $chunk);
3110 $attrParts[] = $str;
3111 $hasInterpolation = true;
3115 if ($this->keyword($word)) {
3116 $attrParts[] = $word;
3120 if ($this->interpolation($inter, false)) {
3121 $attrParts[] = $inter;
3122 $hasInterpolation = true;
3126 // operator, handles attr namespace too
3127 if ($this->match('[|-~\$\*\^=]+', $m)) {
3128 $attrParts[] = $m[0];
3135 if ($this->literal("]", false)) {
3137 foreach ($attrParts as $part) {
3140 $hasExpression = $hasExpression ||
$hasInterpolation;
3150 // a space separated list of selectors
3151 protected function tag(&$tag, $simple = false) {
3153 $chars = '^@,:;{}\][>\(\) "\'';
3155 $chars = '^@,;{}["\'';
3159 $hasExpression = false;
3161 while ($this->tagBracket($parts, $hasExpression));
3163 $oldWhite = $this->eatWhiteDefault
;
3164 $this->eatWhiteDefault
= false;
3167 if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
3171 while ($this->tagBracket($parts, $hasExpression));
3175 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] == "@") {
3176 if ($this->interpolation($interp)) {
3177 $hasExpression = true;
3178 $interp[2] = true; // don't unescape
3183 if ($this->literal("@")) {
3189 if ($this->unit($unit)) { // for keyframes
3190 $parts[] = $unit[1];
3191 $parts[] = $unit[2];
3198 $this->eatWhiteDefault
= $oldWhite;
3204 if ($hasExpression) {
3205 $tag = array("exp", array("string", "", $parts));
3207 $tag = trim(implode($parts));
3210 $this->whitespace();
3215 protected function func(&$func) {
3218 if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
3221 $sPreArgs = $this->seek();
3225 $ss = $this->seek();
3226 // this ugly nonsense is for ie filter properties
3227 if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
3228 $args[] = array("string", "", array($name, "=", $value));
3231 if ($this->expressionList($value)) {
3236 if (!$this->literal(',')) break;
3238 $args = array('list', ',', $args);
3240 if ($this->literal(')')) {
3241 $func = array('function', $fname, $args);
3243 } elseif ($fname == 'url') {
3244 // couldn't parse and in url? treat as string
3245 $this->seek($sPreArgs);
3246 if ($this->openString(")", $string) && $this->literal(")")) {
3247 $func = array('function', $fname, $string);
3257 // consume a less variable
3258 protected function variable(&$name) {
3260 if ($this->literal($this->lessc
->vPrefix
, false) &&
3261 ($this->variable($sub) ||
$this->keyword($name)))
3264 $name = array('variable', $sub);
3266 $name = $this->lessc
->vPrefix
.$name;
3277 * Consume an assignment operator
3278 * Can optionally take a name that will be set to the current property name
3280 protected function assign($name = null) {
3281 if ($name) $this->currentProperty
= $name;
3282 return $this->literal(':') ||
$this->literal('=');
3285 // consume a keyword
3286 protected function keyword(&$word) {
3287 if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
3294 // consume an end of statement delimiter
3295 protected function end() {
3296 if ($this->literal(';')) {
3298 } elseif ($this->count
== strlen($this->buffer
) ||
$this->buffer
[$this->count
] == '}') {
3299 // if there is end of file or a closing block next then we don't need a ;
3305 protected function guards(&$guards) {
3308 if (!$this->literal("when")) {
3315 while ($this->guardGroup($g)) {
3317 if (!$this->literal(",")) break;
3320 if (count($guards) == 0) {
3329 // a bunch of guards that are and'd together
3330 // TODO rename to guardGroup
3331 protected function guardGroup(&$guardGroup) {
3333 $guardGroup = array();
3334 while ($this->guard($guard)) {
3335 $guardGroup[] = $guard;
3336 if (!$this->literal("and")) break;
3339 if (count($guardGroup) == 0) {
3348 protected function guard(&$guard) {
3350 $negate = $this->literal("not");
3352 if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
3354 if ($negate) $guard = array("negate", $guard);
3362 /* raw parsing functions */
3364 protected function literal($what, $eatWhitespace = null) {
3365 if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault
;
3367 // shortcut on single letter
3368 if (!isset($what[1]) && isset($this->buffer
[$this->count
])) {
3369 if ($this->buffer
[$this->count
] == $what) {
3370 if (!$eatWhitespace) {
3380 if (!isset(self
::$literalCache[$what])) {
3381 self
::$literalCache[$what] = lessc
::preg_quote($what);
3384 return $this->match(self
::$literalCache[$what], $m, $eatWhitespace);
3387 protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
3390 while ($this->$parseItem($value)) {
3393 if (!$this->literal($delim)) break;
3397 if (count($items) == 0) {
3402 if ($flatten && count($items) == 1) {
3405 $out = array("list", $delim, $items);
3412 // advance counter to next occurrence of $what
3413 // $until - don't include $what in advance
3414 // $allowNewline, if string, will be used as valid char set
3415 protected function to($what, &$out, $until = false, $allowNewline = false) {
3416 if (is_string($allowNewline)) {
3417 $validChars = $allowNewline;
3419 $validChars = $allowNewline ?
"." : "[^\n]";
3421 if (!$this->match('('.$validChars.'*?)'.lessc
::preg_quote($what), $m, !$until)) return false;
3422 if ($until) $this->count
-= strlen($what); // give back $what
3427 // try to match something on head of buffer
3428 protected function match($regex, &$out, $eatWhitespace = null) {
3429 if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault
;
3431 $r = '/'.$regex.($eatWhitespace && !$this->writeComments ?
'\s*' : '').'/Ais';
3432 if (preg_match($r, $this->buffer
, $out, null, $this->count
)) {
3433 $this->count +
= strlen($out[0]);
3434 if ($eatWhitespace && $this->writeComments
) $this->whitespace();
3440 // match some whitespace
3441 protected function whitespace() {
3442 if ($this->writeComments
) {
3444 while (preg_match(self
::$whitePattern, $this->buffer
, $m, null, $this->count
)) {
3445 if (isset($m[1]) && empty($this->commentsSeen
[$this->count
])) {
3446 $this->append(array("comment", $m[1]));
3447 $this->commentsSeen
[$this->count
] = true;
3449 $this->count +
= strlen($m[0]);
3454 $this->match("", $m);
3455 return strlen($m[0]) > 0;
3459 // match something without consuming it
3460 protected function peek($regex, &$out = null, $from=null) {
3461 if (is_null($from)) $from = $this->count
;
3462 $r = '/'.$regex.'/Ais';
3463 $result = preg_match($r, $this->buffer
, $out, null, $from);
3468 // seek to a spot in the buffer or return where we are on no argument
3469 protected function seek($where = null) {
3470 if ($where === null) return $this->count
;
3471 else $this->count
= $where;
3475 /* misc functions */
3477 public function throwError($msg = "parse error", $count = null) {
3478 $count = is_null($count) ?
$this->count
: $count;
3480 $line = $this->line +
3481 substr_count(substr($this->buffer
, 0, $count), "\n");
3483 if (!empty($this->sourceName
)) {
3484 $loc = "$this->sourceName on line $line";
3486 $loc = "line: $line";
3489 // TODO this depends on $this->count
3490 if ($this->peek("(.*?)(\n|$)", $m, $count)) {
3491 throw new exception("$msg: failed at `$m[1]` $loc");
3493 throw new exception("$msg: $loc");
3497 protected function pushBlock($selectors=null, $type=null) {
3499 $b->parent
= $this->env
;
3502 $b->id
= self
::$nextBlockId++
;
3504 $b->isVararg
= false; // TODO: kill me from here
3505 $b->tags
= $selectors;
3507 $b->props
= array();
3508 $b->children
= array();
3514 // push a block that doesn't multiply tags
3515 protected function pushSpecialBlock($type) {
3516 return $this->pushBlock(null, $type);
3519 // append a property to the current block
3520 protected function append($prop, $pos = null) {
3521 if ($pos !== null) $prop[-1] = $pos;
3522 $this->env
->props
[] = $prop;
3525 // pop something off the stack
3526 protected function pop() {
3528 $this->env
= $this->env
->parent
;
3532 // remove comments from $text
3533 // todo: make it work for all functions, not just url
3534 protected function removeComments($text) {
3536 'url(', '//', '/*', '"', "'"
3542 // find the next item
3543 foreach ($look as $token) {
3544 $pos = strpos($text, $token);
3545 if ($pos !== false) {
3546 if (!isset($min) ||
$pos < $min[1]) $min = array($token, $pos);
3550 if (is_null($min)) break;
3557 if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
3558 $count +
= strlen($m[0]) - strlen($min[0]);
3562 if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count))
3563 $count +
= strlen($m[0]) - 1;
3566 $skip = strpos($text, "\n", $count);
3567 if ($skip === false) $skip = strlen($text) - $count;
3568 else $skip -= $count;
3571 if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
3572 $skip = strlen($m[0]);
3573 $newlines = substr_count($m[0], "\n");
3578 if ($skip == 0) $count +
= strlen($min[0]);
3580 $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
3581 $text = substr($text, $count +
$skip);
3591 class lessc_formatter_classic
{
3592 public $indentChar = " ";
3594 public $break = "\n";
3595 public $open = " {";
3596 public $close = "}";
3597 public $selectorSeparator = ", ";
3598 public $assignSeparator = ":";
3600 public $openSingle = " { ";
3601 public $closeSingle = " }";
3603 public $disableSingle = false;
3604 public $breakSelectors = false;
3606 public $compressColors = false;
3608 public function __construct() {
3609 $this->indentLevel
= 0;
3612 public function indentStr($n = 0) {
3613 return str_repeat($this->indentChar
, max($this->indentLevel +
$n, 0));
3616 public function property($name, $value) {
3617 return $name . $this->assignSeparator
. $value . ";";
3620 protected function isEmpty($block) {
3621 if (empty($block->lines
)) {
3622 foreach ($block->children
as $child) {
3623 if (!$this->isEmpty($child)) return false;
3631 public function block($block) {
3632 if ($this->isEmpty($block)) return;
3634 $inner = $pre = $this->indentStr();
3636 $isSingle = !$this->disableSingle
&&
3637 is_null($block->type
) && count($block->lines
) == 1;
3639 if (!empty($block->selectors
)) {
3640 $this->indentLevel++
;
3642 if ($this->breakSelectors
) {
3643 $selectorSeparator = $this->selectorSeparator
. $this->break . $pre;
3645 $selectorSeparator = $this->selectorSeparator
;
3649 implode($selectorSeparator, $block->selectors
);
3651 echo $this->openSingle
;
3654 echo $this->open
. $this->break;
3655 $inner = $this->indentStr();
3660 if (!empty($block->lines
)) {
3661 $glue = $this->break.$inner;
3662 echo $inner . implode($glue, $block->lines
);
3663 if (!$isSingle && !empty($block->children
)) {
3668 foreach ($block->children
as $child) {
3669 $this->block($child);
3672 if (!empty($block->selectors
)) {
3673 if (!$isSingle && empty($block->children
)) echo $this->break;
3676 echo $this->closeSingle
. $this->break;
3678 echo $pre . $this->close
. $this->break;
3681 $this->indentLevel
--;
3686 class lessc_formatter_compressed
extends lessc_formatter_classic
{
3687 public $disableSingle = true;
3689 public $selectorSeparator = ",";
3690 public $assignSeparator = ":";
3692 public $compressColors = true;
3694 public function indentStr($n = 0) {
3699 class lessc_formatter_lessjs
extends lessc_formatter_classic
{
3700 public $disableSingle = true;
3701 public $breakSelectors = true;
3702 public $assignSeparator = ": ";
3703 public $selectorSeparator = ",";