4 * lessphp v0.4.0@785ad53840
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 public $defaultValue = array("keyword", "");
95 static protected $nextImportId = 0; // uniquely identify imports
97 // attempts to find the path of an import url, returns null for css files
98 protected function findImport($url) {
99 foreach ((array)$this->importDir
as $dir) {
100 $full = $dir.(substr($dir, -1) != '/' ?
'/' : '').$url;
101 if ($this->fileExists($file = $full.'.less') ||
$this->fileExists($file = $full)) {
109 protected function fileExists($name) {
110 return is_file($name);
113 static public function compressList($items, $delim) {
114 if (!isset($items[1]) && isset($items[0])) return $items[0];
115 else return array('list', $delim, $items);
118 static public function preg_quote($what) {
119 return preg_quote($what, '/');
122 protected function tryImport($importPath, $parentBlock, $out) {
123 if ($importPath[0] == "function" && $importPath[1] == "url") {
124 $importPath = $this->flattenList($importPath[2]);
127 $str = $this->coerceString($importPath);
128 if ($str === null) return false;
130 $url = $this->compileValue($this->lib_e($str));
132 // don't import if it ends in css
133 if (substr_compare($url, '.css', -4, 4) === 0) return false;
135 $realPath = $this->findImport($url);
137 if ($realPath === null) return false;
139 if ($this->importDisabled
) {
140 return array(false, "/* import disabled */");
143 if (isset($this->allParsedFiles
[realpath($realPath)])) {
144 return array(false, null);
147 $this->addParsedFile($realPath);
148 $parser = $this->makeParser($realPath);
149 $root = $parser->parse(file_get_contents($realPath));
151 // set the parents of all the block props
152 foreach ($root->props
as $prop) {
153 if ($prop[0] == "block") {
154 $prop[1]->parent
= $parentBlock;
158 // copy mixins into scope, set their parents
159 // bring blocks from import into current block
160 // TODO: need to mark the source parser these came from this file
161 foreach ($root->children
as $childName => $child) {
162 if (isset($parentBlock->children
[$childName])) {
163 $parentBlock->children
[$childName] = array_merge(
164 $parentBlock->children
[$childName],
167 $parentBlock->children
[$childName] = $child;
171 $pi = pathinfo($realPath);
172 $dir = $pi["dirname"];
174 list($top, $bottom) = $this->sortProps($root->props
, true);
175 $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
177 return array(true, $bottom, $parser, $dir);
180 protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
181 $oldSourceParser = $this->sourceParser
;
183 $oldImport = $this->importDir
;
185 // TODO: this is because the importDir api is stupid
186 $this->importDir
= (array)$this->importDir
;
187 array_unshift($this->importDir
, $importDir);
189 foreach ($props as $prop) {
190 $this->compileProp($prop, $block, $out);
193 $this->importDir
= $oldImport;
194 $this->sourceParser
= $oldSourceParser;
198 * Recursively compiles a block.
200 * A block is analogous to a CSS block in most cases. A single LESS document
201 * is encapsulated in a block when parsed, but it does not have parent tags
202 * so all of it's children appear on the root level when compiled.
204 * Blocks are made up of props and children.
206 * Props are property instructions, array tuples which describe an action
207 * to be taken, eg. write a property, set a variable, mixin a block.
209 * The children of a block are just all the blocks that are defined within.
210 * This is used to look up mixins when performing a mixin.
212 * Compiling the block involves pushing a fresh environment on the stack,
213 * and iterating through the props, compiling each one.
215 * See lessc::compileProp()
218 protected function compileBlock($block) {
219 switch ($block->type
) {
221 $this->compileRoot($block);
224 $this->compileCSSBlock($block);
227 $this->compileMedia($block);
230 $name = "@" . $block->name
;
231 if (!empty($block->value
)) {
232 $name .= " " . $this->compileValue($this->reduce($block->value
));
235 $this->compileNestedBlock($block, array($name));
238 $this->throwError("unknown block type: $block->type\n");
242 protected function compileCSSBlock($block) {
243 $env = $this->pushEnv();
245 $selectors = $this->compileSelectors($block->tags
);
246 $env->selectors
= $this->multiplySelectors($selectors);
247 $out = $this->makeOutputBlock(null, $env->selectors
);
249 $this->scope
->children
[] = $out;
250 $this->compileProps($block, $out);
252 $block->scope
= $env; // mixins carry scope with them!
256 protected function compileMedia($media) {
257 $env = $this->pushEnv($media);
258 $parentScope = $this->mediaParent($this->scope
);
260 $query = $this->compileMediaQuery($this->multiplyMedia($env));
262 $this->scope
= $this->makeOutputBlock($media->type
, array($query));
263 $parentScope->children
[] = $this->scope
;
265 $this->compileProps($media, $this->scope
);
267 if (count($this->scope
->lines
) > 0) {
268 $orphanSelelectors = $this->findClosestSelectors();
269 if (!is_null($orphanSelelectors)) {
270 $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
271 $orphan->lines
= $this->scope
->lines
;
272 array_unshift($this->scope
->children
, $orphan);
273 $this->scope
->lines
= array();
277 $this->scope
= $this->scope
->parent
;
281 protected function mediaParent($scope) {
282 while (!empty($scope->parent
)) {
283 if (!empty($scope->type
) && $scope->type
!= "media") {
286 $scope = $scope->parent
;
292 protected function compileNestedBlock($block, $selectors) {
293 $this->pushEnv($block);
294 $this->scope
= $this->makeOutputBlock($block->type
, $selectors);
295 $this->scope
->parent
->children
[] = $this->scope
;
297 $this->compileProps($block, $this->scope
);
299 $this->scope
= $this->scope
->parent
;
303 protected function compileRoot($root) {
305 $this->scope
= $this->makeOutputBlock($root->type
);
306 $this->compileProps($root, $this->scope
);
310 protected function compileProps($block, $out) {
311 foreach ($this->sortProps($block->props
) as $prop) {
312 $this->compileProp($prop, $block, $out);
315 $out->lines
= array_values(array_unique($out->lines
));
318 protected function sortProps($props, $split = false) {
323 foreach ($props as $prop) {
326 if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix
) {
333 $id = self
::$nextImportId++
;
336 $other[] = array("import_mixin", $id);
344 return array(array_merge($vars, $imports), $other);
346 return array_merge($vars, $imports, $other);
350 protected function compileMediaQuery($queries) {
351 $compiledQueries = array();
352 foreach ($queries as $query) {
354 foreach ($query as $q) {
357 $parts[] = implode(" ", array_slice($q, 1));
361 $parts[] = "($q[1]: " .
362 $this->compileValue($this->reduce($q[2])) . ")";
364 $parts[] = "($q[1])";
368 $parts[] = $this->compileValue($this->reduce($q));
373 if (count($parts) > 0) {
374 $compiledQueries[] = implode(" and ", $parts);
379 if (!empty($parts)) {
381 implode($this->formatter
->selectorSeparator
, $compiledQueries);
386 protected function multiplyMedia($env, $childQueries = null) {
388 !empty($env->block
->type
) && $env->block
->type
!= "media")
390 return $childQueries;
393 // plain old block, skip
394 if (empty($env->block
->type
)) {
395 return $this->multiplyMedia($env->parent
, $childQueries);
399 $queries = $env->block
->queries
;
400 if (is_null($childQueries)) {
403 foreach ($queries as $parent) {
404 foreach ($childQueries as $child) {
405 $out[] = array_merge($parent, $child);
410 return $this->multiplyMedia($env->parent
, $out);
413 protected function expandParentSelectors(&$tag, $replace) {
414 $parts = explode("$&$", $tag);
416 foreach ($parts as &$part) {
417 $part = str_replace($this->parentSelector
, $replace, $part, $c);
420 $tag = implode($this->parentSelector
, $parts);
424 protected function findClosestSelectors() {
427 while ($env !== null) {
428 if (isset($env->selectors
)) {
429 $selectors = $env->selectors
;
439 // multiply $selectors against the nearest selectors in env
440 protected function multiplySelectors($selectors) {
441 // find parent selectors
443 $parentSelectors = $this->findClosestSelectors();
444 if (is_null($parentSelectors)) {
445 // kill parent reference in top level selector
446 foreach ($selectors as &$s) {
447 $this->expandParentSelectors($s, "");
454 foreach ($parentSelectors as $parent) {
455 foreach ($selectors as $child) {
456 $count = $this->expandParentSelectors($child, $parent);
458 // don't prepend the parent tag if & was used
460 $out[] = trim($child);
462 $out[] = trim($parent . ' ' . $child);
470 // reduces selector expressions
471 protected function compileSelectors($selectors) {
474 foreach ($selectors as $s) {
477 $out[] = trim($this->compileValue($this->reduce($value)));
486 protected function eq($left, $right) {
487 return $left == $right;
490 protected function patternMatch($block, $orderedArgs, $keywordArgs) {
491 // match the guards if it has them
492 // any one of the groups must have all its guards pass for a match
493 if (!empty($block->guards
)) {
494 $groupPassed = false;
495 foreach ($block->guards
as $guardGroup) {
496 foreach ($guardGroup as $guard) {
498 $this->zipSetArgs($block->args
, $orderedArgs, $keywordArgs);
501 if ($guard[0] == "negate") {
506 $passed = $this->reduce($guard) == self
::$TRUE;
507 if ($negate) $passed = !$passed;
514 $groupPassed = false;
519 if ($groupPassed) break;
527 if (empty($block->args
)) {
528 return $block->isVararg ||
empty($orderedArgs) && empty($keywordArgs);
531 $remainingArgs = $block->args
;
533 $remainingArgs = array();
534 foreach ($block->args
as $arg) {
535 if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
539 $remainingArgs[] = $arg;
544 // try to match by arity or by argument literal
545 foreach ($remainingArgs as $i => $arg) {
548 if (empty($orderedArgs[$i]) ||
!$this->eq($arg[1], $orderedArgs[$i])) {
553 // no arg and no default value
554 if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
559 $i--; // rest can be empty
564 if ($block->isVararg
) {
565 return true; // not having enough is handled above
567 $numMatched = $i +
1;
568 // greater than becuase default values always match
569 return $numMatched >= count($orderedArgs);
573 protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) {
575 foreach ($blocks as $block) {
576 // skip seen blocks that don't have arguments
577 if (isset($skip[$block->id
]) && !isset($block->args
)) {
581 if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
589 // attempt to find blocks matched by path and args
590 protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) {
591 if ($searchIn == null) return null;
592 if (isset($seen[$searchIn->id
])) return null;
593 $seen[$searchIn->id
] = true;
597 if (isset($searchIn->children
[$name])) {
598 $blocks = $searchIn->children
[$name];
599 if (count($path) == 1) {
600 $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
601 if (!empty($matches)) {
602 // This will return all blocks that match in the closest
603 // scope that has any matching block, like lessjs
608 foreach ($blocks as $subBlock) {
609 $subMatches = $this->findBlocks($subBlock,
610 array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
612 if (!is_null($subMatches)) {
613 foreach ($subMatches as $sm) {
619 return count($matches) > 0 ?
$matches : null;
622 if ($searchIn->parent
=== $searchIn) return null;
623 return $this->findBlocks($searchIn->parent
, $path, $orderedArgs, $keywordArgs, $seen);
626 // sets all argument names in $args to either the default value
627 // or the one passed in through $values
628 protected function zipSetArgs($args, $orderedValues, $keywordValues) {
629 $assignedValues = array();
632 foreach ($args as $a) {
633 if ($a[0] == "arg") {
634 if (isset($keywordValues[$a[1]])) {
636 $value = $keywordValues[$a[1]];
637 } elseif (isset($orderedValues[$i])) {
639 $value = $orderedValues[$i];
641 } elseif (isset($a[2])) {
645 $this->throwError("Failed to assign arg " . $a[1]);
649 $value = $this->reduce($value);
650 $this->set($a[1], $value);
651 $assignedValues[] = $value;
660 if ($last[0] == "rest") {
661 $rest = array_slice($orderedValues, count($args) - 1);
662 $this->set($last[1], $this->reduce(array("list", " ", $rest)));
665 // wow is this the only true use of PHP's + operator for arrays?
666 $this->env
->arguments
= $assignedValues +
$orderedValues;
669 // compile a prop and update $lines or $blocks appropriately
670 protected function compileProp($prop, $block, $out) {
671 // set error position context
672 $this->sourceLoc
= isset($prop[-1]) ?
$prop[-1] : -1;
676 list(, $name, $value) = $prop;
677 if ($name[0] == $this->vPrefix
) {
678 $this->set($name, $value);
680 $out->lines
[] = $this->formatter
->property($name,
681 $this->compileValue($this->reduce($value)));
685 list(, $child) = $prop;
686 $this->compileBlock($child);
689 list(, $path, $args, $suffix) = $prop;
691 $orderedArgs = array();
692 $keywordArgs = array();
693 foreach ((array)$args as $arg) {
697 if (!isset($arg[2])) {
698 $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
700 $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
705 $orderedArgs[] = $this->reduce($arg[1]);
708 $this->throwError("Unknown arg type: " . $arg[0]);
712 $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
714 if ($mixins === null) {
715 // fwrite(STDERR,"failed to find block: ".implode(" > ", $path)."\n");
716 break; // throw error here??
719 foreach ($mixins as $mixin) {
720 if ($mixin === $block && !$orderedArgs) {
725 if (isset($mixin->parent
->scope
)) {
727 $mixinParentEnv = $this->pushEnv();
728 $mixinParentEnv->storeParent
= $mixin->parent
->scope
;
732 if (isset($mixin->args
)) {
735 $this->zipSetArgs($mixin->args
, $orderedArgs, $keywordArgs);
738 $oldParent = $mixin->parent
;
739 if ($mixin != $block) $mixin->parent
= $block;
741 foreach ($this->sortProps($mixin->props
) as $subProp) {
742 if ($suffix !== null &&
743 $subProp[0] == "assign" &&
744 is_string($subProp[1]) &&
745 $subProp[1]{0} != $this->vPrefix
)
749 array($subProp[2], array('keyword', $suffix))
753 $this->compileProp($subProp, $mixin, $out);
756 $mixin->parent
= $oldParent;
758 if ($haveArgs) $this->popEnv();
759 if ($haveScope) $this->popEnv();
764 $out->lines
[] = $prop[1];
767 list(, $name, $value) = $prop;
768 $out->lines
[] = "@$name " . $this->compileValue($this->reduce($value)).';';
771 $out->lines
[] = $prop[1];
774 list(, $importPath, $importId) = $prop;
775 $importPath = $this->reduce($importPath);
777 if (!isset($this->env
->imports
)) {
778 $this->env
->imports
= array();
781 $result = $this->tryImport($importPath, $block, $out);
783 $this->env
->imports
[$importId] = $result === false ?
784 array(false, "@import " . $this->compileValue($importPath).";") :
789 list(,$importId) = $prop;
790 $import = $this->env
->imports
[$importId];
791 if ($import[0] === false) {
792 if (isset($import[1])) {
793 $out->lines
[] = $import[1];
796 list(, $bottom, $parser, $importDir) = $import;
797 $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
802 $this->throwError("unknown op: {$prop[0]}\n");
808 * Compiles a primitive value into a CSS property value.
810 * Values in lessphp are typed by being wrapped in arrays, their format is
813 * array(type, contents [, additional_contents]*)
815 * The input is expected to be reduced. This function will not work on
816 * things like expressions and variables.
818 protected function compileValue($value) {
822 // [2] - array of values
823 return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
825 if (!empty($this->formatter
->compressColors
)) {
826 return $this->compileValue($this->coerceColor($value));
833 list(, $num, $unit) = $value;
836 if ($this->numberPrecision
!== null) {
837 $num = round($num, $this->numberPrecision
);
841 // [1] - contents of string (includes quotes)
842 list(, $delim, $content) = $value;
843 foreach ($content as &$part) {
844 if (is_array($part)) {
845 $part = $this->compileValue($part);
848 return $delim . implode($content) . $delim;
850 // [1] - red component (either number or a %)
851 // [2] - green component
852 // [3] - blue component
853 // [4] - optional alpha component
854 list(, $r, $g, $b) = $value;
859 if (count($value) == 5 && $value[4] != 1) { // rgba
860 return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
863 $h = sprintf("#%02x%02x%02x", $r, $g, $b);
865 if (!empty($this->formatter
->compressColors
)) {
866 // Converting hex color to short notation (e.g. #003399 to #039)
867 if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
868 $h = '#' . $h[1] . $h[3] . $h[5];
875 list(, $name, $args) = $value;
876 return $name.'('.$this->compileValue($args).')';
877 default: // assumed to be unit
878 $this->throwError("unknown value type: $value[0]");
882 protected function lib_pow($args) {
883 list($base, $exp) = $this->assertArgs($args, 2, "pow");
884 return pow($this->assertNumber($base), $this->assertNumber($exp));
887 protected function lib_pi() {
891 protected function lib_mod($args) {
892 list($a, $b) = $this->assertArgs($args, 2, "mod");
893 return $this->assertNumber($a) %
$this->assertNumber($b);
896 protected function lib_tan($num) {
897 return tan($this->assertNumber($num));
900 protected function lib_sin($num) {
901 return sin($this->assertNumber($num));
904 protected function lib_cos($num) {
905 return cos($this->assertNumber($num));
908 protected function lib_atan($num) {
909 $num = atan($this->assertNumber($num));
910 return array("number", $num, "rad");
913 protected function lib_asin($num) {
914 $num = asin($this->assertNumber($num));
915 return array("number", $num, "rad");
918 protected function lib_acos($num) {
919 $num = acos($this->assertNumber($num));
920 return array("number", $num, "rad");
923 protected function lib_sqrt($num) {
924 return sqrt($this->assertNumber($num));
927 protected function lib_extract($value) {
928 list($list, $idx) = $this->assertArgs($value, 2, "extract");
929 $idx = $this->assertNumber($idx);
931 if ($list[0] == "list" && isset($list[2][$idx - 1])) {
932 return $list[2][$idx - 1];
936 protected function lib_isnumber($value) {
937 return $this->toBool($value[0] == "number");
940 protected function lib_isstring($value) {
941 return $this->toBool($value[0] == "string");
944 protected function lib_iscolor($value) {
945 return $this->toBool($this->coerceColor($value));
948 protected function lib_iskeyword($value) {
949 return $this->toBool($value[0] == "keyword");
952 protected function lib_ispixel($value) {
953 return $this->toBool($value[0] == "number" && $value[2] == "px");
956 protected function lib_ispercentage($value) {
957 return $this->toBool($value[0] == "number" && $value[2] == "%");
960 protected function lib_isem($value) {
961 return $this->toBool($value[0] == "number" && $value[2] == "em");
964 protected function lib_isrem($value) {
965 return $this->toBool($value[0] == "number" && $value[2] == "rem");
968 protected function lib_rgbahex($color) {
969 $color = $this->coerceColor($color);
971 $this->throwError("color expected for rgbahex");
973 return sprintf("#%02x%02x%02x%02x",
974 isset($color[4]) ?
$color[4]*255 : 255,
975 $color[1],$color[2], $color[3]);
978 protected function lib_argb($color){
979 return $this->lib_rgbahex($color);
982 // utility func to unquote a string
983 protected function lib_e($arg) {
987 if (isset($items[0])) {
988 return $this->lib_e($items[0]);
990 return self
::$defaultValue;
997 return array("keyword", $this->compileValue($arg));
1001 protected function lib__sprintf($args) {
1002 if ($args[0] != "list") return $args;
1004 $string = array_shift($values);
1005 $template = $this->compileValue($this->lib_e($string));
1008 if (preg_match_all('/%[dsa]/', $template, $m)) {
1009 foreach ($m[0] as $match) {
1010 $val = isset($values[$i]) ?
1011 $this->reduce($values[$i]) : array('keyword', '');
1013 // lessjs compat, renders fully expanded color, not raw color
1014 if ($color = $this->coerceColor($val)) {
1019 $rep = $this->compileValue($this->lib_e($val));
1020 $template = preg_replace('/'.self
::preg_quote($match).'/',
1021 $rep, $template, 1);
1025 $d = $string[0] == "string" ?
$string[1] : '"';
1026 return array("string", $d, array($template));
1029 protected function lib_floor($arg) {
1030 $value = $this->assertNumber($arg);
1031 return array("number", floor($value), $arg[2]);
1034 protected function lib_ceil($arg) {
1035 $value = $this->assertNumber($arg);
1036 return array("number", ceil($value), $arg[2]);
1039 protected function lib_round($arg) {
1040 if($arg[0] != "list") {
1041 $value = $this->assertNumber($arg);
1042 return array("number", round($value), $arg[2]);
1044 $value = $this->assertNumber($arg[2][0]);
1045 $precision = $this->assertNumber($arg[2][1]);
1046 return array("number", round($value, $precision), $arg[2][0][2]);
1050 protected function lib_unit($arg) {
1051 if ($arg[0] == "list") {
1052 list($number, $newUnit) = $arg[2];
1053 return array("number", $this->assertNumber($number),
1054 $this->compileValue($this->lib_e($newUnit)));
1056 return array("number", $this->assertNumber($arg), "");
1061 * Helper function to get arguments for color manipulation functions.
1062 * takes a list that contains a color like thing and a percentage
1064 protected function colorArgs($args) {
1065 if ($args[0] != 'list' ||
count($args[2]) < 2) {
1066 return array(array('color', 0, 0, 0), 0);
1068 list($color, $delta) = $args[2];
1069 $color = $this->assertColor($color);
1070 $delta = floatval($delta[1]);
1072 return array($color, $delta);
1075 protected function lib_darken($args) {
1076 list($color, $delta) = $this->colorArgs($args);
1078 $hsl = $this->toHSL($color);
1079 $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
1080 return $this->toRGB($hsl);
1083 protected function lib_lighten($args) {
1084 list($color, $delta) = $this->colorArgs($args);
1086 $hsl = $this->toHSL($color);
1087 $hsl[3] = $this->clamp($hsl[3] +
$delta, 100);
1088 return $this->toRGB($hsl);
1091 protected function lib_saturate($args) {
1092 list($color, $delta) = $this->colorArgs($args);
1094 $hsl = $this->toHSL($color);
1095 $hsl[2] = $this->clamp($hsl[2] +
$delta, 100);
1096 return $this->toRGB($hsl);
1099 protected function lib_desaturate($args) {
1100 list($color, $delta) = $this->colorArgs($args);
1102 $hsl = $this->toHSL($color);
1103 $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
1104 return $this->toRGB($hsl);
1107 protected function lib_spin($args) {
1108 list($color, $delta) = $this->colorArgs($args);
1110 $hsl = $this->toHSL($color);
1112 $hsl[1] = $hsl[1] +
$delta %
360;
1113 if ($hsl[1] < 0) $hsl[1] +
= 360;
1115 return $this->toRGB($hsl);
1118 protected function lib_fadeout($args) {
1119 list($color, $delta) = $this->colorArgs($args);
1120 $color[4] = $this->clamp((isset($color[4]) ?
$color[4] : 1) - $delta/100);
1124 protected function lib_fadein($args) {
1125 list($color, $delta) = $this->colorArgs($args);
1126 $color[4] = $this->clamp((isset($color[4]) ?
$color[4] : 1) +
$delta/100);
1130 protected function lib_hue($color) {
1131 $hsl = $this->toHSL($this->assertColor($color));
1132 return round($hsl[1]);
1135 protected function lib_saturation($color) {
1136 $hsl = $this->toHSL($this->assertColor($color));
1137 return round($hsl[2]);
1140 protected function lib_lightness($color) {
1141 $hsl = $this->toHSL($this->assertColor($color));
1142 return round($hsl[3]);
1145 // get the alpha of a color
1146 // defaults to 1 for non-colors or colors without an alpha
1147 protected function lib_alpha($value) {
1148 if (!is_null($color = $this->coerceColor($value))) {
1149 return isset($color[4]) ?
$color[4] : 1;
1153 // set the alpha of the color
1154 protected function lib_fade($args) {
1155 list($color, $alpha) = $this->colorArgs($args);
1156 $color[4] = $this->clamp($alpha / 100.0);
1160 protected function lib_percentage($arg) {
1161 $num = $this->assertNumber($arg);
1162 return array("number", $num*100, "%");
1165 // mixes two colors by weight
1166 // mix(@color1, @color2, [@weight: 50%]);
1167 // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
1168 protected function lib_mix($args) {
1169 if ($args[0] != "list" ||
count($args[2]) < 2)
1170 $this->throwError("mix expects (color1, color2, weight)");
1172 list($first, $second) = $args[2];
1173 $first = $this->assertColor($first);
1174 $second = $this->assertColor($second);
1176 $first_a = $this->lib_alpha($first);
1177 $second_a = $this->lib_alpha($second);
1179 if (isset($args[2][2])) {
1180 $weight = $args[2][2][1] / 100.0;
1185 $w = $weight * 2 - 1;
1186 $a = $first_a - $second_a;
1188 $w1 = (($w * $a == -1 ?
$w : ($w +
$a)/(1 +
$w * $a)) +
1) / 2.0;
1191 $new = array('color',
1192 $w1 * $first[1] +
$w2 * $second[1],
1193 $w1 * $first[2] +
$w2 * $second[2],
1194 $w1 * $first[3] +
$w2 * $second[3],
1197 if ($first_a != 1.0 ||
$second_a != 1.0) {
1198 $new[] = $first_a * $weight +
$second_a * ($weight - 1);
1201 return $this->fixColor($new);
1204 protected function lib_contrast($args) {
1205 if ($args[0] != 'list' ||
count($args[2]) < 3) {
1206 return array(array('color', 0, 0, 0), 0);
1209 list($inputColor, $darkColor, $lightColor) = $args[2];
1211 $inputColor = $this->assertColor($inputColor);
1212 $darkColor = $this->assertColor($darkColor);
1213 $lightColor = $this->assertColor($lightColor);
1214 $hsl = $this->toHSL($inputColor);
1223 protected function assertColor($value, $error = "expected color value") {
1224 $color = $this->coerceColor($value);
1225 if (is_null($color)) $this->throwError($error);
1229 protected function assertNumber($value, $error = "expecting number") {
1230 if ($value[0] == "number") return $value[1];
1231 $this->throwError($error);
1234 protected function assertArgs($value, $expectedArgs, $name="") {
1235 if ($expectedArgs == 1) {
1238 if ($value[0] !== "list" ||
$value[1] != ",") $this->throwError("expecting list");
1239 $values = $value[2];
1240 $numValues = count($values);
1241 if ($expectedArgs != $numValues) {
1243 $name = $name . ": ";
1246 $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
1253 protected function toHSL($color) {
1254 if ($color[0] == 'hsl') return $color;
1256 $r = $color[1] / 255;
1257 $g = $color[2] / 255;
1258 $b = $color[3] / 255;
1260 $min = min($r, $g, $b);
1261 $max = max($r, $g, $b);
1263 $L = ($min +
$max) / 2;
1268 $S = ($max - $min)/($max +
$min);
1270 $S = ($max - $min)/(2.0 - $max - $min);
1272 if ($r == $max) $H = ($g - $b)/($max - $min);
1273 elseif ($g == $max) $H = 2.0 +
($b - $r)/($max - $min);
1274 elseif ($b == $max) $H = 4.0 +
($r - $g)/($max - $min);
1279 ($H < 0 ?
$H +
6 : $H)*60,
1284 if (count($color) > 4) $out[] = $color[4]; // copy alpha
1288 protected function toRGB_helper($comp, $temp1, $temp2) {
1289 if ($comp < 0) $comp +
= 1.0;
1290 elseif ($comp > 1) $comp -= 1.0;
1292 if (6 * $comp < 1) return $temp1 +
($temp2 - $temp1) * 6 * $comp;
1293 if (2 * $comp < 1) return $temp2;
1294 if (3 * $comp < 2) return $temp1 +
($temp2 - $temp1)*((2/3) - $comp) * 6;
1300 * Converts a hsl array into a color value in rgb.
1301 * Expects H to be in range of 0 to 360, S and L in 0 to 100
1303 protected function toRGB($color) {
1304 if ($color[0] == 'color') return $color;
1306 $H = $color[1] / 360;
1307 $S = $color[2] / 100;
1308 $L = $color[3] / 100;
1317 $temp1 = 2.0 * $L - $temp2;
1319 $r = $this->toRGB_helper($H +
1/3, $temp1, $temp2);
1320 $g = $this->toRGB_helper($H, $temp1, $temp2);
1321 $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
1324 // $out = array('color', round($r*255), round($g*255), round($b*255));
1325 $out = array('color', $r*255, $g*255, $b*255);
1326 if (count($color) > 4) $out[] = $color[4]; // copy alpha
1330 protected function clamp($v, $max = 1, $min = 0) {
1331 return min($max, max($min, $v));
1335 * Convert the rgb, rgba, hsl color literals of function type
1336 * as returned by the parser into values of color type.
1338 protected function funcToColor($func) {
1340 if ($func[2][0] != 'list') return false; // need a list of arguments
1341 $rawComponents = $func[2][2];
1343 if ($fname == 'hsl' ||
$fname == 'hsla') {
1344 $hsl = array('hsl');
1346 foreach ($rawComponents as $c) {
1347 $val = $this->reduce($c);
1348 $val = isset($val[1]) ?
floatval($val[1]) : 0;
1350 if ($i == 0) $clamp = 360;
1351 elseif ($i < 3) $clamp = 100;
1354 $hsl[] = $this->clamp($val, $clamp);
1358 while (count($hsl) < 4) $hsl[] = 0;
1359 return $this->toRGB($hsl);
1361 } elseif ($fname == 'rgb' ||
$fname == 'rgba') {
1362 $components = array();
1364 foreach ($rawComponents as $c) {
1365 $c = $this->reduce($c);
1367 if ($c[0] == "number" && $c[2] == "%") {
1368 $components[] = 255 * ($c[1] / 100);
1370 $components[] = floatval($c[1]);
1372 } elseif ($i == 4) {
1373 if ($c[0] == "number" && $c[2] == "%") {
1374 $components[] = 1.0 * ($c[1] / 100);
1376 $components[] = floatval($c[1]);
1382 while (count($components) < 3) $components[] = 0;
1383 array_unshift($components, 'color');
1384 return $this->fixColor($components);
1390 protected function reduce($value, $forExpression = false) {
1391 switch ($value[0]) {
1393 $reduced = $this->reduce($value[1]);
1394 $var = $this->compileValue($reduced);
1395 $res = $this->reduce(array("variable", $this->vPrefix
. $var));
1397 if ($res[0] == "raw_color") {
1398 $res = $this->coerceColor($res);
1401 if (empty($value[2])) $res = $this->lib_e($res);
1406 if (is_array($key)) {
1407 $key = $this->reduce($key);
1408 $key = $this->vPrefix
. $this->compileValue($this->lib_e($key));
1411 $seen =& $this->env
->seenNames
;
1413 if (!empty($seen[$key])) {
1414 $this->throwError("infinite loop detected: $key");
1418 $out = $this->reduce($this->get($key, self
::$defaultValue));
1419 $seen[$key] = false;
1422 foreach ($value[2] as &$item) {
1423 $item = $this->reduce($item, $forExpression);
1427 return $this->evaluate($value);
1429 foreach ($value[2] as &$part) {
1430 if (is_array($part)) {
1431 $strip = $part[0] == "variable";
1432 $part = $this->reduce($part);
1433 if ($strip) $part = $this->lib_e($part);
1438 list(,$inner) = $value;
1439 return $this->lib_e($this->reduce($inner));
1441 $color = $this->funcToColor($value);
1442 if ($color) return $color;
1444 list(, $name, $args) = $value;
1445 if ($name == "%") $name = "_sprintf";
1446 $f = isset($this->libFunctions
[$name]) ?
1447 $this->libFunctions
[$name] : array($this, 'lib_'.$name);
1449 if (is_callable($f)) {
1450 if ($args[0] == 'list')
1451 $args = self
::compressList($args[2], $args[1]);
1453 $ret = call_user_func($f, $this->reduce($args, true), $this);
1455 if (is_null($ret)) {
1456 return array("string", "", array(
1457 $name, "(", $args, ")"
1461 // convert to a typed value if the result is a php primitive
1462 if (is_numeric($ret)) $ret = array('number', $ret, "");
1463 elseif (!is_array($ret)) $ret = array('keyword', $ret);
1468 // plain function, reduce args
1469 $value[2] = $this->reduce($value[2]);
1472 list(, $op, $exp) = $value;
1473 $exp = $this->reduce($exp);
1475 if ($exp[0] == "number") {
1484 return array("string", "", array($op, $exp));
1487 if ($forExpression) {
1488 switch ($value[0]) {
1490 if ($color = $this->coerceColor($value)) {
1495 return $this->coerceColor($value);
1503 // coerce a value for use in color operation
1504 protected function coerceColor($value) {
1506 case 'color': return $value;
1508 $c = array("color", 0, 0, 0);
1509 $colorStr = substr($value[1], 1);
1510 $num = hexdec($colorStr);
1511 $width = strlen($colorStr) == 3 ?
16 : 256;
1513 for ($i = 3; $i > 0; $i--) { // 3 2 1
1517 $c[$i] = $t * (256/$width) +
$t * floor(16/$width);
1523 if (isset(self
::$cssColors[$name])) {
1524 $rgba = explode(',', self
::$cssColors[$name]);
1527 return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1529 return array('color', $rgba[0], $rgba[1], $rgba[2]);
1535 // make something string like into a string
1536 protected function coerceString($value) {
1537 switch ($value[0]) {
1541 return array("string", "", array($value[1]));
1546 // turn list of length 1 into value type
1547 protected function flattenList($value) {
1548 if ($value[0] == "list" && count($value[2]) == 1) {
1549 return $this->flattenList($value[2][0]);
1554 protected function toBool($a) {
1555 if ($a) return self
::$TRUE;
1556 else return self
::$FALSE;
1559 // evaluate an expression
1560 protected function evaluate($exp) {
1561 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1563 $left = $this->reduce($left, true);
1564 $right = $this->reduce($right, true);
1566 if ($leftColor = $this->coerceColor($left)) {
1570 if ($rightColor = $this->coerceColor($right)) {
1571 $right = $rightColor;
1577 // operators that work on all types
1579 return $this->toBool($left == self
::$TRUE && $right == self
::$TRUE);
1583 return $this->toBool($this->eq($left, $right) );
1586 if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1590 // type based operators
1591 $fname = "op_${ltype}_${rtype}";
1592 if (is_callable(array($this, $fname))) {
1593 $out = $this->$fname($op, $left, $right);
1594 if (!is_null($out)) return $out;
1597 // make the expression look it did before being parsed
1599 if ($whiteBefore) $paddedOp = " " . $paddedOp;
1600 if ($whiteAfter) $paddedOp .= " ";
1602 return array("string", "", array($left, $paddedOp, $right));
1605 protected function stringConcatenate($left, $right) {
1606 if ($strLeft = $this->coerceString($left)) {
1607 if ($right[0] == "string") {
1610 $strLeft[2][] = $right;
1614 if ($strRight = $this->coerceString($right)) {
1615 array_unshift($strRight[2], $left);
1621 // make sure a color's components don't go out of bounds
1622 protected function fixColor($c) {
1623 foreach (range(1, 3) as $i) {
1624 if ($c[$i] < 0) $c[$i] = 0;
1625 if ($c[$i] > 255) $c[$i] = 255;
1631 protected function op_number_color($op, $lft, $rgt) {
1632 if ($op == '+' ||
$op == '*') {
1633 return $this->op_color_number($op, $rgt, $lft);
1637 protected function op_color_number($op, $lft, $rgt) {
1638 if ($rgt[0] == '%') $rgt[1] /= 100;
1640 return $this->op_color_color($op, $lft,
1641 array_fill(1, count($lft) - 1, $rgt[1]));
1644 protected function op_color_color($op, $left, $right) {
1645 $out = array('color');
1646 $max = count($left) > count($right) ?
count($left) : count($right);
1647 foreach (range(1, $max - 1) as $i) {
1648 $lval = isset($left[$i]) ?
$left[$i] : 0;
1649 $rval = isset($right[$i]) ?
$right[$i] : 0;
1652 $out[] = $lval +
$rval;
1655 $out[] = $lval - $rval;
1658 $out[] = $lval * $rval;
1661 $out[] = $lval %
$rval;
1664 if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
1665 $out[] = $lval / $rval;
1668 $this->throwError('evaluate error: color op number failed on op '.$op);
1671 return $this->fixColor($out);
1674 function lib_red($color){
1675 $color = $this->coerceColor($color);
1676 if (is_null($color)) {
1677 $this->throwError('color expected for red()');
1683 function lib_green($color){
1684 $color = $this->coerceColor($color);
1685 if (is_null($color)) {
1686 $this->throwError('color expected for green()');
1692 function lib_blue($color){
1693 $color = $this->coerceColor($color);
1694 if (is_null($color)) {
1695 $this->throwError('color expected for blue()');
1702 // operator on two numbers
1703 protected function op_number_number($op, $left, $right) {
1704 $unit = empty($left[2]) ?
$right[2] : $left[2];
1709 $value = $left[1] +
$right[1];
1712 $value = $left[1] * $right[1];
1715 $value = $left[1] - $right[1];
1718 $value = $left[1] %
$right[1];
1721 if ($right[1] == 0) $this->throwError('parse error: divide by zero');
1722 $value = $left[1] / $right[1];
1725 return $this->toBool($left[1] < $right[1]);
1727 return $this->toBool($left[1] > $right[1]);
1729 return $this->toBool($left[1] >= $right[1]);
1731 return $this->toBool($left[1] <= $right[1]);
1733 $this->throwError('parse error: unknown number operator: '.$op);
1736 return array("number", $value, $unit);
1740 /* environment functions */
1742 protected function makeOutputBlock($type, $selectors = null) {
1744 $b->lines
= array();
1745 $b->children
= array();
1746 $b->selectors
= $selectors;
1748 $b->parent
= $this->scope
;
1752 // the state of execution
1753 protected function pushEnv($block = null) {
1755 $e->parent
= $this->env
;
1756 $e->store
= array();
1763 // pop something off the stack
1764 protected function popEnv() {
1766 $this->env
= $this->env
->parent
;
1770 // set something in the current env
1771 protected function set($name, $value) {
1772 $this->env
->store
[$name] = $value;
1776 // get the highest occurrence entry for a name
1777 protected function get($name, $default=null) {
1778 $current = $this->env
;
1780 $isArguments = $name == $this->vPrefix
. 'arguments';
1782 if ($isArguments && isset($current->arguments
)) {
1783 return array('list', ' ', $current->arguments
);
1786 if (isset($current->store
[$name]))
1787 return $current->store
[$name];
1789 $current = isset($current->storeParent
) ?
1790 $current->storeParent
: $current->parent
;
1797 // inject array of unparsed strings into environment as variables
1798 protected function injectVariables($args) {
1800 $parser = new lessc_parser($this, __METHOD__
);
1801 foreach ($args as $name => $strValue) {
1802 if ($name{0} != '@') $name = '@'.$name;
1804 $parser->buffer
= (string)$strValue;
1805 if (!$parser->propertyValue($value)) {
1806 throw new Exception("failed to parse passed in variable $name: $strValue");
1809 $this->set($name, $value);
1814 * Initialize any static state, can initialize parser for a file
1815 * $opts isn't used yet
1817 public function __construct($fname = null) {
1818 if ($fname !== null) {
1819 // used for deprecated parse method
1820 $this->_parseFile
= $fname;
1824 public function compile($string, $name = null) {
1825 $locale = setlocale(LC_NUMERIC
, 0);
1826 setlocale(LC_NUMERIC
, "C");
1828 $this->parser
= $this->makeParser($name);
1829 $root = $this->parser
->parse($string);
1832 $this->scope
= null;
1834 $this->formatter
= $this->newFormatter();
1836 if (!empty($this->registeredVars
)) {
1837 $this->injectVariables($this->registeredVars
);
1840 $this->sourceParser
= $this->parser
; // used for error messages
1841 $this->compileBlock($root);
1844 $this->formatter
->block($this->scope
);
1845 $out = ob_get_clean();
1846 setlocale(LC_NUMERIC
, $locale);
1850 public function compileFile($fname, $outFname = null) {
1851 if (!is_readable($fname)) {
1852 throw new Exception('load error: failed to find '.$fname);
1855 $pi = pathinfo($fname);
1857 $oldImport = $this->importDir
;
1859 $this->importDir
= (array)$this->importDir
;
1860 $this->importDir
[] = $pi['dirname'].'/';
1862 $this->addParsedFile($fname);
1864 $out = $this->compile(file_get_contents($fname), $fname);
1866 $this->importDir
= $oldImport;
1868 if ($outFname !== null) {
1869 return file_put_contents($outFname, $out);
1875 // compile only if changed input has changed or output doesn't exist
1876 public function checkedCompile($in, $out) {
1877 if (!is_file($out) ||
filemtime($in) > filemtime($out)) {
1878 $this->compileFile($in, $out);
1885 * Execute lessphp on a .less file or a lessphp cache structure
1887 * The lessphp cache structure contains information about a specific
1888 * less file having been parsed. It can be used as a hint for future
1889 * calls to determine whether or not a rebuild is required.
1891 * The cache structure contains two important keys that may be used
1894 * compiled: The final compiled CSS
1895 * updated: The time (in seconds) the CSS was last compiled
1897 * The cache structure is a plain-ol' PHP associative array and can
1898 * be serialized and unserialized without a hitch.
1900 * @param mixed $in Input
1901 * @param bool $force Force rebuild?
1902 * @return array lessphp cache structure
1904 public function cachedCompile($in, $force = false) {
1908 if (is_string($in)) {
1910 } elseif (is_array($in) and isset($in['root'])) {
1911 if ($force or ! isset($in['files'])) {
1912 // If we are forcing a recompile or if for some reason the
1913 // structure does not contain any file information we should
1914 // specify the root to trigger a rebuild.
1915 $root = $in['root'];
1916 } elseif (isset($in['files']) and is_array($in['files'])) {
1917 foreach ($in['files'] as $fname => $ftime ) {
1918 if (!file_exists($fname) or filemtime($fname) > $ftime) {
1919 // One of the files we knew about previously has changed
1920 // so we should look at our incoming root again.
1921 $root = $in['root'];
1927 // TODO: Throw an exception? We got neither a string nor something
1928 // that looks like a compatible lessphp cache structure.
1932 if ($root !== null) {
1933 // If we have a root value which means we should rebuild.
1935 $out['root'] = $root;
1936 $out['compiled'] = $this->compileFile($root);
1937 $out['files'] = $this->allParsedFiles();
1938 $out['updated'] = time();
1941 // No changes, pass back the structure
1942 // we were given initially.
1948 // parse and compile buffer
1949 // This is deprecated
1950 public function parse($str = null, $initialVariables = null) {
1951 if (is_array($str)) {
1952 $initialVariables = $str;
1956 $oldVars = $this->registeredVars
;
1957 if ($initialVariables !== null) {
1958 $this->setVariables($initialVariables);
1962 if (empty($this->_parseFile
)) {
1963 throw new exception("nothing to parse");
1966 $out = $this->compileFile($this->_parseFile
);
1968 $out = $this->compile($str);
1971 $this->registeredVars
= $oldVars;
1975 protected function makeParser($name) {
1976 $parser = new lessc_parser($this, $name);
1977 $parser->writeComments
= $this->preserveComments
;
1982 public function setFormatter($name) {
1983 $this->formatterName
= $name;
1986 protected function newFormatter() {
1987 $className = "lessc_formatter_lessjs";
1988 if (!empty($this->formatterName
)) {
1989 if (!is_string($this->formatterName
))
1990 return $this->formatterName
;
1991 $className = "lessc_formatter_$this->formatterName";
1994 return new $className;
1997 public function setPreserveComments($preserve) {
1998 $this->preserveComments
= $preserve;
2001 public function registerFunction($name, $func) {
2002 $this->libFunctions
[$name] = $func;
2005 public function unregisterFunction($name) {
2006 unset($this->libFunctions
[$name]);
2009 public function setVariables($variables) {
2010 $this->registeredVars
= array_merge($this->registeredVars
, $variables);
2013 public function unsetVariable($name) {
2014 unset($this->registeredVars
[$name]);
2017 public function setImportDir($dirs) {
2018 $this->importDir
= (array)$dirs;
2021 public function addImportDir($dir) {
2022 $this->importDir
= (array)$this->importDir
;
2023 $this->importDir
[] = $dir;
2026 public function allParsedFiles() {
2027 return $this->allParsedFiles
;
2030 protected function addParsedFile($file) {
2031 $this->allParsedFiles
[realpath($file)] = filemtime($file);
2035 * Uses the current value of $this->count to show line and line number
2037 protected function throwError($msg = null) {
2038 if ($this->sourceLoc
>= 0) {
2039 $this->sourceParser
->throwError($msg, $this->sourceLoc
);
2041 throw new exception($msg);
2044 // compile file $in to file $out if $in is newer than $out
2045 // returns true when it compiles, false otherwise
2046 public static function ccompile($in, $out, $less = null) {
2047 if ($less === null) {
2050 return $less->checkedCompile($in, $out);
2053 public static function cexecute($in, $force = false, $less = null) {
2054 if ($less === null) {
2057 return $less->cachedCompile($in, $force);
2060 static protected $cssColors = array(
2061 'aliceblue' => '240,248,255',
2062 'antiquewhite' => '250,235,215',
2063 'aqua' => '0,255,255',
2064 'aquamarine' => '127,255,212',
2065 'azure' => '240,255,255',
2066 'beige' => '245,245,220',
2067 'bisque' => '255,228,196',
2069 'blanchedalmond' => '255,235,205',
2070 'blue' => '0,0,255',
2071 'blueviolet' => '138,43,226',
2072 'brown' => '165,42,42',
2073 'burlywood' => '222,184,135',
2074 'cadetblue' => '95,158,160',
2075 'chartreuse' => '127,255,0',
2076 'chocolate' => '210,105,30',
2077 'coral' => '255,127,80',
2078 'cornflowerblue' => '100,149,237',
2079 'cornsilk' => '255,248,220',
2080 'crimson' => '220,20,60',
2081 'cyan' => '0,255,255',
2082 'darkblue' => '0,0,139',
2083 'darkcyan' => '0,139,139',
2084 'darkgoldenrod' => '184,134,11',
2085 'darkgray' => '169,169,169',
2086 'darkgreen' => '0,100,0',
2087 'darkgrey' => '169,169,169',
2088 'darkkhaki' => '189,183,107',
2089 'darkmagenta' => '139,0,139',
2090 'darkolivegreen' => '85,107,47',
2091 'darkorange' => '255,140,0',
2092 'darkorchid' => '153,50,204',
2093 'darkred' => '139,0,0',
2094 'darksalmon' => '233,150,122',
2095 'darkseagreen' => '143,188,143',
2096 'darkslateblue' => '72,61,139',
2097 'darkslategray' => '47,79,79',
2098 'darkslategrey' => '47,79,79',
2099 'darkturquoise' => '0,206,209',
2100 'darkviolet' => '148,0,211',
2101 'deeppink' => '255,20,147',
2102 'deepskyblue' => '0,191,255',
2103 'dimgray' => '105,105,105',
2104 'dimgrey' => '105,105,105',
2105 'dodgerblue' => '30,144,255',
2106 'firebrick' => '178,34,34',
2107 'floralwhite' => '255,250,240',
2108 'forestgreen' => '34,139,34',
2109 'fuchsia' => '255,0,255',
2110 'gainsboro' => '220,220,220',
2111 'ghostwhite' => '248,248,255',
2112 'gold' => '255,215,0',
2113 'goldenrod' => '218,165,32',
2114 'gray' => '128,128,128',
2115 'green' => '0,128,0',
2116 'greenyellow' => '173,255,47',
2117 'grey' => '128,128,128',
2118 'honeydew' => '240,255,240',
2119 'hotpink' => '255,105,180',
2120 'indianred' => '205,92,92',
2121 'indigo' => '75,0,130',
2122 'ivory' => '255,255,240',
2123 'khaki' => '240,230,140',
2124 'lavender' => '230,230,250',
2125 'lavenderblush' => '255,240,245',
2126 'lawngreen' => '124,252,0',
2127 'lemonchiffon' => '255,250,205',
2128 'lightblue' => '173,216,230',
2129 'lightcoral' => '240,128,128',
2130 'lightcyan' => '224,255,255',
2131 'lightgoldenrodyellow' => '250,250,210',
2132 'lightgray' => '211,211,211',
2133 'lightgreen' => '144,238,144',
2134 'lightgrey' => '211,211,211',
2135 'lightpink' => '255,182,193',
2136 'lightsalmon' => '255,160,122',
2137 'lightseagreen' => '32,178,170',
2138 'lightskyblue' => '135,206,250',
2139 'lightslategray' => '119,136,153',
2140 'lightslategrey' => '119,136,153',
2141 'lightsteelblue' => '176,196,222',
2142 'lightyellow' => '255,255,224',
2143 'lime' => '0,255,0',
2144 'limegreen' => '50,205,50',
2145 'linen' => '250,240,230',
2146 'magenta' => '255,0,255',
2147 'maroon' => '128,0,0',
2148 'mediumaquamarine' => '102,205,170',
2149 'mediumblue' => '0,0,205',
2150 'mediumorchid' => '186,85,211',
2151 'mediumpurple' => '147,112,219',
2152 'mediumseagreen' => '60,179,113',
2153 'mediumslateblue' => '123,104,238',
2154 'mediumspringgreen' => '0,250,154',
2155 'mediumturquoise' => '72,209,204',
2156 'mediumvioletred' => '199,21,133',
2157 'midnightblue' => '25,25,112',
2158 'mintcream' => '245,255,250',
2159 'mistyrose' => '255,228,225',
2160 'moccasin' => '255,228,181',
2161 'navajowhite' => '255,222,173',
2162 'navy' => '0,0,128',
2163 'oldlace' => '253,245,230',
2164 'olive' => '128,128,0',
2165 'olivedrab' => '107,142,35',
2166 'orange' => '255,165,0',
2167 'orangered' => '255,69,0',
2168 'orchid' => '218,112,214',
2169 'palegoldenrod' => '238,232,170',
2170 'palegreen' => '152,251,152',
2171 'paleturquoise' => '175,238,238',
2172 'palevioletred' => '219,112,147',
2173 'papayawhip' => '255,239,213',
2174 'peachpuff' => '255,218,185',
2175 'peru' => '205,133,63',
2176 'pink' => '255,192,203',
2177 'plum' => '221,160,221',
2178 'powderblue' => '176,224,230',
2179 'purple' => '128,0,128',
2181 'rosybrown' => '188,143,143',
2182 'royalblue' => '65,105,225',
2183 'saddlebrown' => '139,69,19',
2184 'salmon' => '250,128,114',
2185 'sandybrown' => '244,164,96',
2186 'seagreen' => '46,139,87',
2187 'seashell' => '255,245,238',
2188 'sienna' => '160,82,45',
2189 'silver' => '192,192,192',
2190 'skyblue' => '135,206,235',
2191 'slateblue' => '106,90,205',
2192 'slategray' => '112,128,144',
2193 'slategrey' => '112,128,144',
2194 'snow' => '255,250,250',
2195 'springgreen' => '0,255,127',
2196 'steelblue' => '70,130,180',
2197 'tan' => '210,180,140',
2198 'teal' => '0,128,128',
2199 'thistle' => '216,191,216',
2200 'tomato' => '255,99,71',
2201 'transparent' => '0,0,0,0',
2202 'turquoise' => '64,224,208',
2203 'violet' => '238,130,238',
2204 'wheat' => '245,222,179',
2205 'white' => '255,255,255',
2206 'whitesmoke' => '245,245,245',
2207 'yellow' => '255,255,0',
2208 'yellowgreen' => '154,205,50'
2212 // responsible for taking a string of LESS code and converting it into a
2214 class lessc_parser
{
2215 static protected $nextBlockId = 0; // used to uniquely identify blocks
2217 static protected $precedence = array(
2231 static protected $whitePattern;
2232 static protected $commentMulti;
2234 static protected $commentSingle = "//";
2235 static protected $commentMultiLeft = "/*";
2236 static protected $commentMultiRight = "*/";
2238 // regex string to match any of the operators
2239 static protected $operatorString;
2241 // these properties will supress division unless it's inside parenthases
2242 static protected $supressDivisionProps =
2243 array('/border-radius$/i', '/^font$/i');
2245 protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
2246 protected $lineDirectives = array("charset");
2249 * if we are in parens we can be more liberal with whitespace around
2250 * operators because it must evaluate to a single value and thus is less
2254 * property1: 10 -5; // is two numbers, 10 and -5
2255 * property2: (10 -5); // should evaluate to 5
2257 protected $inParens = false;
2259 // caches preg escaped literals
2260 static protected $literalCache = array();
2262 public function __construct($lessc, $sourceName = null) {
2263 $this->eatWhiteDefault
= true;
2264 // reference to less needed for vPrefix, mPrefix, and parentSelector
2265 $this->lessc
= $lessc;
2267 $this->sourceName
= $sourceName; // name used for error messages
2269 $this->writeComments
= false;
2271 if (!self
::$operatorString) {
2272 self
::$operatorString =
2273 '('.implode('|', array_map(array('lessc', 'preg_quote'),
2274 array_keys(self
::$precedence))).')';
2276 $commentSingle = lessc
::preg_quote(self
::$commentSingle);
2277 $commentMultiLeft = lessc
::preg_quote(self
::$commentMultiLeft);
2278 $commentMultiRight = lessc
::preg_quote(self
::$commentMultiRight);
2280 self
::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
2281 self
::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self
::$commentMulti.')\s*|\s+/Ais';
2285 public function parse($buffer) {
2289 $this->env
= null; // block stack
2290 $this->buffer
= $this->writeComments ?
$buffer : $this->removeComments($buffer);
2291 $this->pushSpecialBlock("root");
2292 $this->eatWhiteDefault
= true;
2293 $this->seenComments
= array();
2295 // trim whitespace on head
2296 // if (preg_match('/^\s+/', $this->buffer, $m)) {
2297 // $this->line += substr_count($m[0], "\n");
2298 // $this->buffer = ltrim($this->buffer);
2300 $this->whitespace();
2302 // parse the entire file
2303 $lastCount = $this->count
;
2304 while (false !== $this->parseChunk());
2306 if ($this->count
!= strlen($this->buffer
))
2307 $this->throwError();
2309 // TODO report where the block was opened
2310 if (!is_null($this->env
->parent
))
2311 throw new exception('parse error: unclosed block');
2317 * Parse a single chunk off the head of the buffer and append it to the
2318 * current parse environment.
2319 * Returns false when the buffer is empty, or when there is an error.
2321 * This function is called repeatedly until the entire document is
2324 * This parser is most similar to a recursive descent parser. Single
2325 * functions represent discrete grammatical rules for the language, and
2326 * they are able to capture the text that represents those rules.
2328 * Consider the function lessc::keyword(). (all parse functions are
2329 * structured the same)
2331 * The function takes a single reference argument. When calling the
2332 * function it will attempt to match a keyword on the head of the buffer.
2333 * If it is successful, it will place the keyword in the referenced
2334 * argument, advance the position in the buffer, and return true. If it
2335 * fails then it won't advance the buffer and it will return false.
2337 * All of these parse functions are powered by lessc::match(), which behaves
2338 * the same way, but takes a literal regular expression. Sometimes it is
2339 * more convenient to use match instead of creating a new function.
2341 * Because of the format of the functions, to parse an entire string of
2342 * grammatical rules, you can chain them together using &&.
2344 * But, if some of the rules in the chain succeed before one fails, then
2345 * the buffer position will be left at an invalid state. In order to
2346 * avoid this, lessc::seek() is used to remember and set buffer positions.
2348 * Before parsing a chain, use $s = $this->seek() to remember the current
2349 * position into $s. Then if a chain fails, use $this->seek($s) to
2350 * go back where we started.
2352 protected function parseChunk() {
2353 if (empty($this->buffer
)) return false;
2356 // setting a property
2357 if ($this->keyword($key) && $this->assign() &&
2358 $this->propertyValue($value, $key) && $this->end())
2360 $this->append(array('assign', $key, $value), $s);
2367 // look for special css blocks
2368 if ($this->literal('@', false)) {
2372 if ($this->literal('@media')) {
2373 if (($this->mediaQueryList($mediaQueries) ||
true)
2374 && $this->literal('{'))
2376 $media = $this->pushSpecialBlock("media");
2377 $media->queries
= is_null($mediaQueries) ?
array() : $mediaQueries;
2385 if ($this->literal("@", false) && $this->keyword($dirName)) {
2386 if ($this->isDirective($dirName, $this->blockDirectives
)) {
2387 if (($this->openString("{", $dirValue, null, array(";")) ||
true) &&
2388 $this->literal("{"))
2390 $dir = $this->pushSpecialBlock("directive");
2391 $dir->name
= $dirName;
2392 if (isset($dirValue)) $dir->value
= $dirValue;
2395 } elseif ($this->isDirective($dirName, $this->lineDirectives
)) {
2396 if ($this->propertyValue($dirValue) && $this->end()) {
2397 $this->append(array("directive", $dirName, $dirValue));
2406 // setting a variable
2407 if ($this->variable($var) && $this->assign() &&
2408 $this->propertyValue($value) && $this->end())
2410 $this->append(array('assign', $var, $value), $s);
2416 if ($this->import($importValue)) {
2417 $this->append($importValue, $s);
2421 // opening parametric mixin
2422 if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
2423 ($this->guards($guards) ||
true) &&
2424 $this->literal('{'))
2426 $block = $this->pushBlock($this->fixTags(array($tag)));
2427 $block->args
= $args;
2428 $block->isVararg
= $isVararg;
2429 if (!empty($guards)) $block->guards
= $guards;
2435 // opening a simple block
2436 if ($this->tags($tags) && $this->literal('{')) {
2437 $tags = $this->fixTags($tags);
2438 $this->pushBlock($tags);
2445 if ($this->literal('}', false)) {
2447 $block = $this->pop();
2448 } catch (exception
$e) {
2450 $this->throwError($e->getMessage());
2454 if (is_null($block->type
)) {
2456 if (!isset($block->args
)) {
2457 foreach ($block->tags
as $tag) {
2458 if (!is_string($tag) ||
$tag{0} != $this->lessc
->mPrefix
) {
2465 foreach ($block->tags
as $tag) {
2466 if (is_string($tag)) {
2467 $this->env
->children
[$tag][] = $block;
2473 $this->append(array('block', $block), $s);
2476 // this is done here so comments aren't bundled into he block that
2478 $this->whitespace();
2483 if ($this->mixinTags($tags) &&
2484 ($this->argumentDef($argv, $isVararg) ||
true) &&
2485 ($this->keyword($suffix) ||
true) && $this->end())
2487 $tags = $this->fixTags($tags);
2488 $this->append(array('mixin', $tags, $argv, $suffix), $s);
2495 if ($this->literal(';')) return true;
2497 return false; // got nothing, throw error
2500 protected function isDirective($dirname, $directives) {
2501 // TODO: cache pattern in parser
2502 $pattern = implode("|",
2503 array_map(array("lessc", "preg_quote"), $directives));
2504 $pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
2506 return preg_match($pattern, $dirname);
2509 protected function fixTags($tags) {
2510 // move @ tags out of variable namespace
2511 foreach ($tags as &$tag) {
2512 if ($tag{0} == $this->lessc
->vPrefix
)
2513 $tag[0] = $this->lessc
->mPrefix
;
2518 // a list of expressions
2519 protected function expressionList(&$exps) {
2522 while ($this->expression($exp)) {
2526 if (count($values) == 0) return false;
2528 $exps = lessc
::compressList($values, ' ');
2533 * Attempt to consume an expression.
2534 * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
2536 protected function expression(&$out) {
2537 if ($this->value($lhs)) {
2538 $out = $this->expHelper($lhs, 0);
2540 // look for / shorthand
2541 if (!empty($this->env
->supressedDivision
)) {
2542 unset($this->env
->supressedDivision
);
2544 if ($this->literal("/") && $this->value($rhs)) {
2545 $out = array("list", "",
2546 array($out, array("keyword", "/"), $rhs));
2558 * recursively parse infix equation with $lhs at precedence $minP
2560 protected function expHelper($lhs, $minP) {
2561 $this->inExp
= true;
2562 $ss = $this->seek();
2565 $whiteBefore = isset($this->buffer
[$this->count
- 1]) &&
2566 ctype_space($this->buffer
[$this->count
- 1]);
2568 // If there is whitespace before the operator, then we require
2569 // whitespace after the operator for it to be an expression
2570 $needWhite = $whiteBefore && !$this->inParens
;
2572 if ($this->match(self
::$operatorString.($needWhite ?
'\s' : ''), $m) && self
::$precedence[$m[1]] >= $minP) {
2573 if (!$this->inParens
&& isset($this->env
->currentProperty
) && $m[1] == "/" && empty($this->env
->supressedDivision
)) {
2574 foreach (self
::$supressDivisionProps as $pattern) {
2575 if (preg_match($pattern, $this->env
->currentProperty
)) {
2576 $this->env
->supressedDivision
= true;
2583 $whiteAfter = isset($this->buffer
[$this->count
- 1]) &&
2584 ctype_space($this->buffer
[$this->count
- 1]);
2586 if (!$this->value($rhs)) break;
2588 // peek for next operator to see what to do with rhs
2589 if ($this->peek(self
::$operatorString, $next) && self
::$precedence[$next[1]] > self
::$precedence[$m[1]]) {
2590 $rhs = $this->expHelper($rhs, self
::$precedence[$next[1]]);
2593 $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
2594 $ss = $this->seek();
2607 // consume a list of values for a property
2608 public function propertyValue(&$value, $keyName = null) {
2611 if ($keyName !== null) $this->env
->currentProperty
= $keyName;
2614 while ($this->expressionList($v)) {
2617 if (!$this->literal(',')) break;
2620 if ($s) $this->seek($s);
2622 if ($keyName !== null) unset($this->env
->currentProperty
);
2624 if (count($values) == 0) return false;
2626 $value = lessc
::compressList($values, ', ');
2630 protected function parenValue(&$out) {
2634 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] != "(") {
2638 $inParens = $this->inParens
;
2639 if ($this->literal("(") &&
2640 ($this->inParens
= true) && $this->expression($exp) &&
2641 $this->literal(")"))
2644 $this->inParens
= $inParens;
2647 $this->inParens
= $inParens;
2655 protected function value(&$value) {
2659 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] == "-") {
2661 if ($this->literal("-", false) &&
2662 (($this->variable($inner) && $inner = array("variable", $inner)) ||
2663 $this->unit($inner) ||
2664 $this->parenValue($inner)))
2666 $value = array("unary", "-", $inner);
2673 if ($this->parenValue($value)) return true;
2674 if ($this->unit($value)) return true;
2675 if ($this->color($value)) return true;
2676 if ($this->func($value)) return true;
2677 if ($this->string($value)) return true;
2679 if ($this->keyword($word)) {
2680 $value = array('keyword', $word);
2685 if ($this->variable($var)) {
2686 $value = array('variable', $var);
2690 // unquote string (should this work on any type?
2691 if ($this->literal("~") && $this->string($str)) {
2692 $value = array("escape", $str);
2699 if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
2700 $value = array('keyword', '\\'.$m[1]);
2709 // an import statement
2710 protected function import(&$out) {
2712 if (!$this->literal('@import')) return false;
2714 // @import "something.css" media;
2715 // @import url("something.css") media;
2716 // @import url(something.css) media;
2718 if ($this->propertyValue($value)) {
2719 $out = array("import", $value);
2724 protected function mediaQueryList(&$out) {
2725 if ($this->genericList($list, "mediaQuery", ",", false)) {
2732 protected function mediaQuery(&$out) {
2735 $expressions = null;
2738 if (($this->literal("only") && ($only = true) ||
$this->literal("not") && ($not = true) ||
true) && $this->keyword($mediaType)) {
2739 $prop = array("mediaType");
2740 if (isset($only)) $prop[] = "only";
2741 if (isset($not)) $prop[] = "not";
2742 $prop[] = $mediaType;
2749 if (!empty($mediaType) && !$this->literal("and")) {
2752 $this->genericList($expressions, "mediaExpression", "and", false);
2753 if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
2756 if (count($parts) == 0) {
2765 protected function mediaExpression(&$out) {
2768 if ($this->literal("(") &&
2769 $this->keyword($feature) &&
2770 ($this->literal(":") && $this->expression($value) ||
true) &&
2771 $this->literal(")"))
2773 $out = array("mediaExp", $feature);
2774 if ($value) $out[] = $value;
2776 } elseif ($this->variable($variable)) {
2777 $out = array('variable', $variable);
2785 // an unbounded string stopped by $end
2786 protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) {
2787 $oldWhite = $this->eatWhiteDefault
;
2788 $this->eatWhiteDefault
= false;
2790 $stop = array("'", '"', "@{", $end);
2791 $stop = array_map(array("lessc", "preg_quote"), $stop);
2792 // $stop[] = self::$commentMulti;
2794 if (!is_null($rejectStrs)) {
2795 $stop = array_merge($stop, $rejectStrs);
2798 $patt = '(.*?)('.implode("|", $stop).')';
2803 while ($this->match($patt, $m, false)) {
2804 if (!empty($m[1])) {
2807 $nestingLevel +
= substr_count($m[1], $nestingOpen);
2813 $this->count
-= strlen($tok);
2815 if ($nestingLevel == 0) {
2822 if (($tok == "'" ||
$tok == '"') && $this->string($str)) {
2827 if ($tok == "@{" && $this->interpolation($inter)) {
2828 $content[] = $inter;
2832 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
2837 $this->count+
= strlen($tok);
2840 $this->eatWhiteDefault
= $oldWhite;
2842 if (count($content) == 0) return false;
2845 if (is_string(end($content))) {
2846 $content[count($content) - 1] = rtrim(end($content));
2849 $out = array("string", "", $content);
2853 protected function string(&$out) {
2855 if ($this->literal('"', false)) {
2857 } elseif ($this->literal("'", false)) {
2865 // look for either ending delim , escape, or string interpolation
2866 $patt = '([^\n]*?)(@\{|\\\\|' .
2867 lessc
::preg_quote($delim).')';
2869 $oldWhite = $this->eatWhiteDefault
;
2870 $this->eatWhiteDefault
= false;
2872 while ($this->match($patt, $m, false)) {
2874 if ($m[2] == "@{") {
2875 $this->count
-= strlen($m[2]);
2876 if ($this->interpolation($inter, false)) {
2877 $content[] = $inter;
2879 $this->count +
= strlen($m[2]);
2880 $content[] = "@{"; // ignore it
2882 } elseif ($m[2] == '\\') {
2884 if ($this->literal($delim, false)) {
2885 $content[] = $delim;
2888 $this->count
-= strlen($delim);
2893 $this->eatWhiteDefault
= $oldWhite;
2895 if ($this->literal($delim)) {
2896 $out = array("string", $delim, $content);
2904 protected function interpolation(&$out) {
2905 $oldWhite = $this->eatWhiteDefault
;
2906 $this->eatWhiteDefault
= true;
2909 if ($this->literal("@{") &&
2910 $this->openString("}", $interp, null, array("'", '"', ";")) &&
2911 $this->literal("}", false))
2913 $out = array("interpolate", $interp);
2914 $this->eatWhiteDefault
= $oldWhite;
2915 if ($this->eatWhiteDefault
) $this->whitespace();
2919 $this->eatWhiteDefault
= $oldWhite;
2924 protected function unit(&$unit) {
2926 if (isset($this->buffer
[$this->count
])) {
2927 $char = $this->buffer
[$this->count
];
2928 if (!ctype_digit($char) && $char != ".") return false;
2931 if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
2932 $unit = array("number", $m[1], empty($m[2]) ?
"" : $m[2]);
2939 protected function color(&$out) {
2940 if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
2941 if (strlen($m[1]) > 7) {
2942 $out = array("string", "", array($m[1]));
2944 $out = array("raw_color", $m[1]);
2952 // consume an argument definition list surrounded by ()
2953 // each argument is a variable name with optional value
2954 // or at the end a ... or a variable named followed by ...
2955 // arguments are separated by , unless a ; is in the list, then ; is the
2957 protected function argumentDef(&$args, &$isVararg) {
2959 if (!$this->literal('(')) return false;
2963 $method = "expressionList";
2967 if ($this->literal("...")) {
2972 if ($this->$method($value)) {
2973 if ($value[0] == "variable") {
2974 $arg = array("arg", $value[1]);
2975 $ss = $this->seek();
2977 if ($this->assign() && $this->$method($rhs)) {
2981 if ($this->literal("...")) {
2988 if ($isVararg) break;
2991 $values[] = array("lit", $value);
2996 if (!$this->literal($delim)) {
2997 if ($delim == "," && $this->literal(";")) {
2998 // found new delim, convert existing args
3000 $method = "propertyValue";
3002 // transform arg list
3003 if (isset($values[1])) { // 2 items
3005 foreach ($values as $i => $arg) {
3009 $this->throwError("Cannot mix ; and , as delimiter types");
3011 $newList[] = $arg[2];
3014 $newList[] = $arg[1];
3017 $this->throwError("Unexpected rest before semicolon");
3021 $newList = array("list", ", ", $newList);
3023 switch ($values[0][0]) {
3025 $newArg = array("arg", $values[0][1], $newList);
3028 $newArg = array("lit", $newList);
3032 } elseif ($values) { // 1 item
3033 $newArg = $values[0];
3037 $values = array($newArg);
3045 if (!$this->literal(')')) {
3055 // consume a list of tags
3056 // this accepts a hanging delimiter
3057 protected function tags(&$tags, $simple = false, $delim = ',') {
3059 while ($this->tag($tt, $simple)) {
3061 if (!$this->literal($delim)) break;
3063 if (count($tags) == 0) return false;
3068 // list of tags of specifying mixin path
3069 // optionally separated by > (lazy, accepts extra >)
3070 protected function mixinTags(&$tags) {
3073 while ($this->tag($tt, true)) {
3075 $this->literal(">");
3078 if (count($tags) == 0) return false;
3083 // a bracketed value (contained within in a tag definition)
3084 protected function tagBracket(&$parts, &$hasExpression) {
3086 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] != "[") {
3092 $hasInterpolation = false;
3094 if ($this->literal("[", false)) {
3095 $attrParts = array("[");
3096 // keyword, string, operator
3098 if ($this->literal("]", false)) {
3100 break; // get out early
3103 if ($this->match('\s+', $m)) {
3107 if ($this->string($str)) {
3108 // escape parent selector, (yuck)
3109 foreach ($str[2] as &$chunk) {
3110 $chunk = str_replace($this->lessc
->parentSelector
, "$&$", $chunk);
3113 $attrParts[] = $str;
3114 $hasInterpolation = true;
3118 if ($this->keyword($word)) {
3119 $attrParts[] = $word;
3123 if ($this->interpolation($inter, false)) {
3124 $attrParts[] = $inter;
3125 $hasInterpolation = true;
3129 // operator, handles attr namespace too
3130 if ($this->match('[|-~\$\*\^=]+', $m)) {
3131 $attrParts[] = $m[0];
3138 if ($this->literal("]", false)) {
3140 foreach ($attrParts as $part) {
3143 $hasExpression = $hasExpression ||
$hasInterpolation;
3153 // a space separated list of selectors
3154 protected function tag(&$tag, $simple = false) {
3156 $chars = '^@,:;{}\][>\(\) "\'';
3158 $chars = '^@,;{}["\'';
3162 $hasExpression = false;
3164 while ($this->tagBracket($parts, $hasExpression));
3166 $oldWhite = $this->eatWhiteDefault
;
3167 $this->eatWhiteDefault
= false;
3170 if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
3174 while ($this->tagBracket($parts, $hasExpression));
3178 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] == "@") {
3179 if ($this->interpolation($interp)) {
3180 $hasExpression = true;
3181 $interp[2] = true; // don't unescape
3186 if ($this->literal("@")) {
3192 if ($this->unit($unit)) { // for keyframes
3193 $parts[] = $unit[1];
3194 $parts[] = $unit[2];
3201 $this->eatWhiteDefault
= $oldWhite;
3207 if ($hasExpression) {
3208 $tag = array("exp", array("string", "", $parts));
3210 $tag = trim(implode($parts));
3213 $this->whitespace();
3218 protected function func(&$func) {
3221 if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
3224 $sPreArgs = $this->seek();
3228 $ss = $this->seek();
3229 // this ugly nonsense is for ie filter properties
3230 if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
3231 $args[] = array("string", "", array($name, "=", $value));
3234 if ($this->expressionList($value)) {
3239 if (!$this->literal(',')) break;
3241 $args = array('list', ',', $args);
3243 if ($this->literal(')')) {
3244 $func = array('function', $fname, $args);
3246 } elseif ($fname == 'url') {
3247 // couldn't parse and in url? treat as string
3248 $this->seek($sPreArgs);
3249 if ($this->openString(")", $string) && $this->literal(")")) {
3250 $func = array('function', $fname, $string);
3260 // consume a less variable
3261 protected function variable(&$name) {
3263 if ($this->literal($this->lessc
->vPrefix
, false) &&
3264 ($this->variable($sub) ||
$this->keyword($name)))
3267 $name = array('variable', $sub);
3269 $name = $this->lessc
->vPrefix
.$name;
3280 * Consume an assignment operator
3281 * Can optionally take a name that will be set to the current property name
3283 protected function assign($name = null) {
3284 if ($name) $this->currentProperty
= $name;
3285 return $this->literal(':') ||
$this->literal('=');
3288 // consume a keyword
3289 protected function keyword(&$word) {
3290 if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
3297 // consume an end of statement delimiter
3298 protected function end() {
3299 if ($this->literal(';')) {
3301 } elseif ($this->count
== strlen($this->buffer
) ||
$this->buffer
[$this->count
] == '}') {
3302 // if there is end of file or a closing block next then we don't need a ;
3308 protected function guards(&$guards) {
3311 if (!$this->literal("when")) {
3318 while ($this->guardGroup($g)) {
3320 if (!$this->literal(",")) break;
3323 if (count($guards) == 0) {
3332 // a bunch of guards that are and'd together
3333 // TODO rename to guardGroup
3334 protected function guardGroup(&$guardGroup) {
3336 $guardGroup = array();
3337 while ($this->guard($guard)) {
3338 $guardGroup[] = $guard;
3339 if (!$this->literal("and")) break;
3342 if (count($guardGroup) == 0) {
3351 protected function guard(&$guard) {
3353 $negate = $this->literal("not");
3355 if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
3357 if ($negate) $guard = array("negate", $guard);
3365 /* raw parsing functions */
3367 protected function literal($what, $eatWhitespace = null) {
3368 if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault
;
3370 // shortcut on single letter
3371 if (!isset($what[1]) && isset($this->buffer
[$this->count
])) {
3372 if ($this->buffer
[$this->count
] == $what) {
3373 if (!$eatWhitespace) {
3383 if (!isset(self
::$literalCache[$what])) {
3384 self
::$literalCache[$what] = lessc
::preg_quote($what);
3387 return $this->match(self
::$literalCache[$what], $m, $eatWhitespace);
3390 protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
3393 while ($this->$parseItem($value)) {
3396 if (!$this->literal($delim)) break;
3400 if (count($items) == 0) {
3405 if ($flatten && count($items) == 1) {
3408 $out = array("list", $delim, $items);
3415 // advance counter to next occurrence of $what
3416 // $until - don't include $what in advance
3417 // $allowNewline, if string, will be used as valid char set
3418 protected function to($what, &$out, $until = false, $allowNewline = false) {
3419 if (is_string($allowNewline)) {
3420 $validChars = $allowNewline;
3422 $validChars = $allowNewline ?
"." : "[^\n]";
3424 if (!$this->match('('.$validChars.'*?)'.lessc
::preg_quote($what), $m, !$until)) return false;
3425 if ($until) $this->count
-= strlen($what); // give back $what
3430 // try to match something on head of buffer
3431 protected function match($regex, &$out, $eatWhitespace = null) {
3432 if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault
;
3434 $r = '/'.$regex.($eatWhitespace && !$this->writeComments ?
'\s*' : '').'/Ais';
3435 if (preg_match($r, $this->buffer
, $out, null, $this->count
)) {
3436 $this->count +
= strlen($out[0]);
3437 if ($eatWhitespace && $this->writeComments
) $this->whitespace();
3443 // match some whitespace
3444 protected function whitespace() {
3445 if ($this->writeComments
) {
3447 while (preg_match(self
::$whitePattern, $this->buffer
, $m, null, $this->count
)) {
3448 if (isset($m[1]) && empty($this->commentsSeen
[$this->count
])) {
3449 $this->append(array("comment", $m[1]));
3450 $this->commentsSeen
[$this->count
] = true;
3452 $this->count +
= strlen($m[0]);
3457 $this->match("", $m);
3458 return strlen($m[0]) > 0;
3462 // match something without consuming it
3463 protected function peek($regex, &$out = null, $from=null) {
3464 if (is_null($from)) $from = $this->count
;
3465 $r = '/'.$regex.'/Ais';
3466 $result = preg_match($r, $this->buffer
, $out, null, $from);
3471 // seek to a spot in the buffer or return where we are on no argument
3472 protected function seek($where = null) {
3473 if ($where === null) return $this->count
;
3474 else $this->count
= $where;
3478 /* misc functions */
3480 public function throwError($msg = "parse error", $count = null) {
3481 $count = is_null($count) ?
$this->count
: $count;
3483 $line = $this->line +
3484 substr_count(substr($this->buffer
, 0, $count), "\n");
3486 if (!empty($this->sourceName
)) {
3487 $loc = "$this->sourceName on line $line";
3489 $loc = "line: $line";
3492 // TODO this depends on $this->count
3493 if ($this->peek("(.*?)(\n|$)", $m, $count)) {
3494 throw new exception("$msg: failed at `$m[1]` $loc");
3496 throw new exception("$msg: $loc");
3500 protected function pushBlock($selectors=null, $type=null) {
3502 $b->parent
= $this->env
;
3505 $b->id
= self
::$nextBlockId++
;
3507 $b->isVararg
= false; // TODO: kill me from here
3508 $b->tags
= $selectors;
3510 $b->props
= array();
3511 $b->children
= array();
3517 // push a block that doesn't multiply tags
3518 protected function pushSpecialBlock($type) {
3519 return $this->pushBlock(null, $type);
3522 // append a property to the current block
3523 protected function append($prop, $pos = null) {
3524 if ($pos !== null) $prop[-1] = $pos;
3525 $this->env
->props
[] = $prop;
3528 // pop something off the stack
3529 protected function pop() {
3531 $this->env
= $this->env
->parent
;
3535 // remove comments from $text
3536 // todo: make it work for all functions, not just url
3537 protected function removeComments($text) {
3539 'url(', '//', '/*', '"', "'"
3545 // find the next item
3546 foreach ($look as $token) {
3547 $pos = strpos($text, $token);
3548 if ($pos !== false) {
3549 if (!isset($min) ||
$pos < $min[1]) $min = array($token, $pos);
3553 if (is_null($min)) break;
3560 if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
3561 $count +
= strlen($m[0]) - strlen($min[0]);
3565 if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count))
3566 $count +
= strlen($m[0]) - 1;
3569 $skip = strpos($text, "\n", $count);
3570 if ($skip === false) $skip = strlen($text) - $count;
3571 else $skip -= $count;
3574 if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
3575 $skip = strlen($m[0]);
3576 $newlines = substr_count($m[0], "\n");
3581 if ($skip == 0) $count +
= strlen($min[0]);
3583 $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
3584 $text = substr($text, $count +
$skip);
3594 class lessc_formatter_classic
{
3595 public $indentChar = " ";
3597 public $break = "\n";
3598 public $open = " {";
3599 public $close = "}";
3600 public $selectorSeparator = ", ";
3601 public $assignSeparator = ":";
3603 public $openSingle = " { ";
3604 public $closeSingle = " }";
3606 public $disableSingle = false;
3607 public $breakSelectors = false;
3609 public $compressColors = false;
3611 public function __construct() {
3612 $this->indentLevel
= 0;
3615 public function indentStr($n = 0) {
3616 return str_repeat($this->indentChar
, max($this->indentLevel +
$n, 0));
3619 public function property($name, $value) {
3620 return $name . $this->assignSeparator
. $value . ";";
3623 protected function isEmpty($block) {
3624 if (empty($block->lines
)) {
3625 foreach ($block->children
as $child) {
3626 if (!$this->isEmpty($child)) return false;
3634 public function block($block) {
3635 if ($this->isEmpty($block)) return;
3637 $inner = $pre = $this->indentStr();
3639 $isSingle = !$this->disableSingle
&&
3640 is_null($block->type
) && count($block->lines
) == 1;
3642 if (!empty($block->selectors
)) {
3643 $this->indentLevel++
;
3645 if ($this->breakSelectors
) {
3646 $selectorSeparator = $this->selectorSeparator
. $this->break . $pre;
3648 $selectorSeparator = $this->selectorSeparator
;
3652 implode($selectorSeparator, $block->selectors
);
3654 echo $this->openSingle
;
3657 echo $this->open
. $this->break;
3658 $inner = $this->indentStr();
3663 if (!empty($block->lines
)) {
3664 $glue = $this->break.$inner;
3665 echo $inner . implode($glue, $block->lines
);
3666 if (!$isSingle && !empty($block->children
)) {
3671 foreach ($block->children
as $child) {
3672 $this->block($child);
3675 if (!empty($block->selectors
)) {
3676 if (!$isSingle && empty($block->children
)) echo $this->break;
3679 echo $this->closeSingle
. $this->break;
3681 echo $pre . $this->close
. $this->break;
3684 $this->indentLevel
--;
3689 class lessc_formatter_compressed
extends lessc_formatter_classic
{
3690 public $disableSingle = true;
3692 public $selectorSeparator = ",";
3693 public $assignSeparator = ":";
3695 public $compressColors = true;
3697 public function indentStr($n = 0) {
3702 class lessc_formatter_lessjs
extends lessc_formatter_classic
{
3703 public $disableSingle = true;
3704 public $breakSelectors = true;
3705 public $assignSeparator = ": ";
3706 public $selectorSeparator = ",";