Merge "Add option to chose what language to fetch file description in."
[lhc/web/wiklou.git] / includes / libs / lessc.inc.php
1 <?php
2
3 /**
4 * lessphp v0.4.0@785ad53840
5 * http://leafo.net/lessphp
6 *
7 * LESS css compiler, adapted from http://lesscss.org
8 *
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.
11 *
12 * MIT LICENSE
13 *
14 * Copyright 2013, Leaf Corcoran <leafot@gmail.com>
15 *
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:
23 *
24 * The above copyright notice and this permission notice shall be
25 * included in all copies or substantial portions of the Software.
26 *
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.
34 *
35 * GPL VERSION 3
36 *
37 * Please refer to http://www.gnu.org/licenses/gpl-3.0.html for the full
38 * text of the GPL version 3
39 */
40
41
42 /**
43 * The less compiler and parser.
44 *
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.
49 *
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.
53 *
54 * The `parse` function of `lessc` is the entry point.
55 *
56 * In summary:
57 *
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
61 * time.
62 *
63 * The `lessc_parser` class is only concerned with parsing its input.
64 *
65 * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
66 * handling things like indentation.
67 */
68 class lessc {
69 static public $VERSION = "v0.4.0";
70 static protected $TRUE = array("keyword", "true");
71 static protected $FALSE = array("keyword", "false");
72
73 protected $libFunctions = array();
74 protected $registeredVars = array();
75 protected $preserveComments = false;
76
77 public $vPrefix = '@'; // prefix of abstract properties
78 public $mPrefix = '$'; // prefix of abstract blocks
79 public $parentSelector = '&';
80
81 public $importDisabled = false;
82 public $importDir = '';
83
84 protected $numberPrecision = null;
85
86 protected $allParsedFiles = array();
87
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;
92
93 static public $defaultValue = array("keyword", "");
94
95 static protected $nextImportId = 0; // uniquely identify imports
96
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)) {
102 return $file;
103 }
104 }
105
106 return null;
107 }
108
109 protected function fileExists($name) {
110 return is_file($name);
111 }
112
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);
116 }
117
118 static public function preg_quote($what) {
119 return preg_quote($what, '/');
120 }
121
122 protected function tryImport($importPath, $parentBlock, $out) {
123 if ($importPath[0] == "function" && $importPath[1] == "url") {
124 $importPath = $this->flattenList($importPath[2]);
125 }
126
127 $str = $this->coerceString($importPath);
128 if ($str === null) return false;
129
130 $url = $this->compileValue($this->lib_e($str));
131
132 // don't import if it ends in css
133 if (substr_compare($url, '.css', -4, 4) === 0) return false;
134
135 $realPath = $this->findImport($url);
136
137 if ($realPath === null) return false;
138
139 if ($this->importDisabled) {
140 return array(false, "/* import disabled */");
141 }
142
143 if (isset($this->allParsedFiles[realpath($realPath)])) {
144 return array(false, null);
145 }
146
147 $this->addParsedFile($realPath);
148 $parser = $this->makeParser($realPath);
149 $root = $parser->parse(file_get_contents($realPath));
150
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;
155 }
156 }
157
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],
165 $child);
166 } else {
167 $parentBlock->children[$childName] = $child;
168 }
169 }
170
171 $pi = pathinfo($realPath);
172 $dir = $pi["dirname"];
173
174 list($top, $bottom) = $this->sortProps($root->props, true);
175 $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
176
177 return array(true, $bottom, $parser, $dir);
178 }
179
180 protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
181 $oldSourceParser = $this->sourceParser;
182
183 $oldImport = $this->importDir;
184
185 // TODO: this is because the importDir api is stupid
186 $this->importDir = (array)$this->importDir;
187 array_unshift($this->importDir, $importDir);
188
189 foreach ($props as $prop) {
190 $this->compileProp($prop, $block, $out);
191 }
192
193 $this->importDir = $oldImport;
194 $this->sourceParser = $oldSourceParser;
195 }
196
197 /**
198 * Recursively compiles a block.
199 *
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.
203 *
204 * Blocks are made up of props and children.
205 *
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.
208 *
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.
211 *
212 * Compiling the block involves pushing a fresh environment on the stack,
213 * and iterating through the props, compiling each one.
214 *
215 * See lessc::compileProp()
216 *
217 */
218 protected function compileBlock($block) {
219 switch ($block->type) {
220 case "root":
221 $this->compileRoot($block);
222 break;
223 case null:
224 $this->compileCSSBlock($block);
225 break;
226 case "media":
227 $this->compileMedia($block);
228 break;
229 case "directive":
230 $name = "@" . $block->name;
231 if (!empty($block->value)) {
232 $name .= " " . $this->compileValue($this->reduce($block->value));
233 }
234
235 $this->compileNestedBlock($block, array($name));
236 break;
237 default:
238 $this->throwError("unknown block type: $block->type\n");
239 }
240 }
241
242 protected function compileCSSBlock($block) {
243 $env = $this->pushEnv();
244
245 $selectors = $this->compileSelectors($block->tags);
246 $env->selectors = $this->multiplySelectors($selectors);
247 $out = $this->makeOutputBlock(null, $env->selectors);
248
249 $this->scope->children[] = $out;
250 $this->compileProps($block, $out);
251
252 $block->scope = $env; // mixins carry scope with them!
253 $this->popEnv();
254 }
255
256 protected function compileMedia($media) {
257 $env = $this->pushEnv($media);
258 $parentScope = $this->mediaParent($this->scope);
259
260 $query = $this->compileMediaQuery($this->multiplyMedia($env));
261
262 $this->scope = $this->makeOutputBlock($media->type, array($query));
263 $parentScope->children[] = $this->scope;
264
265 $this->compileProps($media, $this->scope);
266
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();
274 }
275 }
276
277 $this->scope = $this->scope->parent;
278 $this->popEnv();
279 }
280
281 protected function mediaParent($scope) {
282 while (!empty($scope->parent)) {
283 if (!empty($scope->type) && $scope->type != "media") {
284 break;
285 }
286 $scope = $scope->parent;
287 }
288
289 return $scope;
290 }
291
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;
296
297 $this->compileProps($block, $this->scope);
298
299 $this->scope = $this->scope->parent;
300 $this->popEnv();
301 }
302
303 protected function compileRoot($root) {
304 $this->pushEnv();
305 $this->scope = $this->makeOutputBlock($root->type);
306 $this->compileProps($root, $this->scope);
307 $this->popEnv();
308 }
309
310 protected function compileProps($block, $out) {
311 foreach ($this->sortProps($block->props) as $prop) {
312 $this->compileProp($prop, $block, $out);
313 }
314
315 $out->lines = array_values(array_unique($out->lines));
316 }
317
318 protected function sortProps($props, $split = false) {
319 $vars = array();
320 $imports = array();
321 $other = array();
322
323 foreach ($props as $prop) {
324 switch ($prop[0]) {
325 case "assign":
326 if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) {
327 $vars[] = $prop;
328 } else {
329 $other[] = $prop;
330 }
331 break;
332 case "import":
333 $id = self::$nextImportId++;
334 $prop[] = $id;
335 $imports[] = $prop;
336 $other[] = array("import_mixin", $id);
337 break;
338 default:
339 $other[] = $prop;
340 }
341 }
342
343 if ($split) {
344 return array(array_merge($vars, $imports), $other);
345 } else {
346 return array_merge($vars, $imports, $other);
347 }
348 }
349
350 protected function compileMediaQuery($queries) {
351 $compiledQueries = array();
352 foreach ($queries as $query) {
353 $parts = array();
354 foreach ($query as $q) {
355 switch ($q[0]) {
356 case "mediaType":
357 $parts[] = implode(" ", array_slice($q, 1));
358 break;
359 case "mediaExp":
360 if (isset($q[2])) {
361 $parts[] = "($q[1]: " .
362 $this->compileValue($this->reduce($q[2])) . ")";
363 } else {
364 $parts[] = "($q[1])";
365 }
366 break;
367 case "variable":
368 $parts[] = $this->compileValue($this->reduce($q));
369 break;
370 }
371 }
372
373 if (count($parts) > 0) {
374 $compiledQueries[] = implode(" and ", $parts);
375 }
376 }
377
378 $out = "@media";
379 if (!empty($parts)) {
380 $out .= " " .
381 implode($this->formatter->selectorSeparator, $compiledQueries);
382 }
383 return $out;
384 }
385
386 protected function multiplyMedia($env, $childQueries = null) {
387 if (is_null($env) ||
388 !empty($env->block->type) && $env->block->type != "media")
389 {
390 return $childQueries;
391 }
392
393 // plain old block, skip
394 if (empty($env->block->type)) {
395 return $this->multiplyMedia($env->parent, $childQueries);
396 }
397
398 $out = array();
399 $queries = $env->block->queries;
400 if (is_null($childQueries)) {
401 $out = $queries;
402 } else {
403 foreach ($queries as $parent) {
404 foreach ($childQueries as $child) {
405 $out[] = array_merge($parent, $child);
406 }
407 }
408 }
409
410 return $this->multiplyMedia($env->parent, $out);
411 }
412
413 protected function expandParentSelectors(&$tag, $replace) {
414 $parts = explode("$&$", $tag);
415 $count = 0;
416 foreach ($parts as &$part) {
417 $part = str_replace($this->parentSelector, $replace, $part, $c);
418 $count += $c;
419 }
420 $tag = implode($this->parentSelector, $parts);
421 return $count;
422 }
423
424 protected function findClosestSelectors() {
425 $env = $this->env;
426 $selectors = null;
427 while ($env !== null) {
428 if (isset($env->selectors)) {
429 $selectors = $env->selectors;
430 break;
431 }
432 $env = $env->parent;
433 }
434
435 return $selectors;
436 }
437
438
439 // multiply $selectors against the nearest selectors in env
440 protected function multiplySelectors($selectors) {
441 // find parent selectors
442
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, "");
448 }
449
450 return $selectors;
451 }
452
453 $out = array();
454 foreach ($parentSelectors as $parent) {
455 foreach ($selectors as $child) {
456 $count = $this->expandParentSelectors($child, $parent);
457
458 // don't prepend the parent tag if & was used
459 if ($count > 0) {
460 $out[] = trim($child);
461 } else {
462 $out[] = trim($parent . ' ' . $child);
463 }
464 }
465 }
466
467 return $out;
468 }
469
470 // reduces selector expressions
471 protected function compileSelectors($selectors) {
472 $out = array();
473
474 foreach ($selectors as $s) {
475 if (is_array($s)) {
476 list(, $value) = $s;
477 $out[] = trim($this->compileValue($this->reduce($value)));
478 } else {
479 $out[] = $s;
480 }
481 }
482
483 return $out;
484 }
485
486 protected function eq($left, $right) {
487 return $left == $right;
488 }
489
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) {
497 $this->pushEnv();
498 $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
499
500 $negate = false;
501 if ($guard[0] == "negate") {
502 $guard = $guard[1];
503 $negate = true;
504 }
505
506 $passed = $this->reduce($guard) == self::$TRUE;
507 if ($negate) $passed = !$passed;
508
509 $this->popEnv();
510
511 if ($passed) {
512 $groupPassed = true;
513 } else {
514 $groupPassed = false;
515 break;
516 }
517 }
518
519 if ($groupPassed) break;
520 }
521
522 if (!$groupPassed) {
523 return false;
524 }
525 }
526
527 if (empty($block->args)) {
528 return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
529 }
530
531 $remainingArgs = $block->args;
532 if ($keywordArgs) {
533 $remainingArgs = array();
534 foreach ($block->args as $arg) {
535 if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
536 continue;
537 }
538
539 $remainingArgs[] = $arg;
540 }
541 }
542
543 $i = -1; // no args
544 // try to match by arity or by argument literal
545 foreach ($remainingArgs as $i => $arg) {
546 switch ($arg[0]) {
547 case "lit":
548 if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
549 return false;
550 }
551 break;
552 case "arg":
553 // no arg and no default value
554 if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
555 return false;
556 }
557 break;
558 case "rest":
559 $i--; // rest can be empty
560 break 2;
561 }
562 }
563
564 if ($block->isVararg) {
565 return true; // not having enough is handled above
566 } else {
567 $numMatched = $i + 1;
568 // greater than becuase default values always match
569 return $numMatched >= count($orderedArgs);
570 }
571 }
572
573 protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) {
574 $matches = null;
575 foreach ($blocks as $block) {
576 // skip seen blocks that don't have arguments
577 if (isset($skip[$block->id]) && !isset($block->args)) {
578 continue;
579 }
580
581 if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
582 $matches[] = $block;
583 }
584 }
585
586 return $matches;
587 }
588
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;
594
595 $name = $path[0];
596
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
604 return $matches;
605 }
606 } else {
607 $matches = array();
608 foreach ($blocks as $subBlock) {
609 $subMatches = $this->findBlocks($subBlock,
610 array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
611
612 if (!is_null($subMatches)) {
613 foreach ($subMatches as $sm) {
614 $matches[] = $sm;
615 }
616 }
617 }
618
619 return count($matches) > 0 ? $matches : null;
620 }
621 }
622 if ($searchIn->parent === $searchIn) return null;
623 return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
624 }
625
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();
630
631 $i = 0;
632 foreach ($args as $a) {
633 if ($a[0] == "arg") {
634 if (isset($keywordValues[$a[1]])) {
635 // has keyword arg
636 $value = $keywordValues[$a[1]];
637 } elseif (isset($orderedValues[$i])) {
638 // has ordered arg
639 $value = $orderedValues[$i];
640 $i++;
641 } elseif (isset($a[2])) {
642 // has default value
643 $value = $a[2];
644 } else {
645 $this->throwError("Failed to assign arg " . $a[1]);
646 $value = null; // :(
647 }
648
649 $value = $this->reduce($value);
650 $this->set($a[1], $value);
651 $assignedValues[] = $value;
652 } else {
653 // a lit
654 $i++;
655 }
656 }
657
658 // check for a rest
659 $last = end($args);
660 if ($last[0] == "rest") {
661 $rest = array_slice($orderedValues, count($args) - 1);
662 $this->set($last[1], $this->reduce(array("list", " ", $rest)));
663 }
664
665 // wow is this the only true use of PHP's + operator for arrays?
666 $this->env->arguments = $assignedValues + $orderedValues;
667 }
668
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;
673
674 switch ($prop[0]) {
675 case 'assign':
676 list(, $name, $value) = $prop;
677 if ($name[0] == $this->vPrefix) {
678 $this->set($name, $value);
679 } else {
680 $out->lines[] = $this->formatter->property($name,
681 $this->compileValue($this->reduce($value)));
682 }
683 break;
684 case 'block':
685 list(, $child) = $prop;
686 $this->compileBlock($child);
687 break;
688 case 'mixin':
689 list(, $path, $args, $suffix) = $prop;
690
691 $orderedArgs = array();
692 $keywordArgs = array();
693 foreach ((array)$args as $arg) {
694 $argval = null;
695 switch ($arg[0]) {
696 case "arg":
697 if (!isset($arg[2])) {
698 $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
699 } else {
700 $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
701 }
702 break;
703
704 case "lit":
705 $orderedArgs[] = $this->reduce($arg[1]);
706 break;
707 default:
708 $this->throwError("Unknown arg type: " . $arg[0]);
709 }
710 }
711
712 $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
713
714 if ($mixins === null) {
715 // fwrite(STDERR,"failed to find block: ".implode(" > ", $path)."\n");
716 break; // throw error here??
717 }
718
719 foreach ($mixins as $mixin) {
720 if ($mixin === $block && !$orderedArgs) {
721 continue;
722 }
723
724 $haveScope = false;
725 if (isset($mixin->parent->scope)) {
726 $haveScope = true;
727 $mixinParentEnv = $this->pushEnv();
728 $mixinParentEnv->storeParent = $mixin->parent->scope;
729 }
730
731 $haveArgs = false;
732 if (isset($mixin->args)) {
733 $haveArgs = true;
734 $this->pushEnv();
735 $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs);
736 }
737
738 $oldParent = $mixin->parent;
739 if ($mixin != $block) $mixin->parent = $block;
740
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)
746 {
747 $subProp[2] = array(
748 'list', ' ',
749 array($subProp[2], array('keyword', $suffix))
750 );
751 }
752
753 $this->compileProp($subProp, $mixin, $out);
754 }
755
756 $mixin->parent = $oldParent;
757
758 if ($haveArgs) $this->popEnv();
759 if ($haveScope) $this->popEnv();
760 }
761
762 break;
763 case 'raw':
764 $out->lines[] = $prop[1];
765 break;
766 case "directive":
767 list(, $name, $value) = $prop;
768 $out->lines[] = "@$name " . $this->compileValue($this->reduce($value)).';';
769 break;
770 case "comment":
771 $out->lines[] = $prop[1];
772 break;
773 case "import";
774 list(, $importPath, $importId) = $prop;
775 $importPath = $this->reduce($importPath);
776
777 if (!isset($this->env->imports)) {
778 $this->env->imports = array();
779 }
780
781 $result = $this->tryImport($importPath, $block, $out);
782
783 $this->env->imports[$importId] = $result === false ?
784 array(false, "@import " . $this->compileValue($importPath).";") :
785 $result;
786
787 break;
788 case "import_mixin":
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];
794 }
795 } else {
796 list(, $bottom, $parser, $importDir) = $import;
797 $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
798 }
799
800 break;
801 default:
802 $this->throwError("unknown op: {$prop[0]}\n");
803 }
804 }
805
806
807 /**
808 * Compiles a primitive value into a CSS property value.
809 *
810 * Values in lessphp are typed by being wrapped in arrays, their format is
811 * typically:
812 *
813 * array(type, contents [, additional_contents]*)
814 *
815 * The input is expected to be reduced. This function will not work on
816 * things like expressions and variables.
817 */
818 protected function compileValue($value) {
819 switch ($value[0]) {
820 case 'list':
821 // [1] - delimiter
822 // [2] - array of values
823 return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
824 case 'raw_color':
825 if (!empty($this->formatter->compressColors)) {
826 return $this->compileValue($this->coerceColor($value));
827 }
828 return $value[1];
829 case 'keyword':
830 // [1] - the keyword
831 return $value[1];
832 case 'number':
833 list(, $num, $unit) = $value;
834 // [1] - the number
835 // [2] - the unit
836 if ($this->numberPrecision !== null) {
837 $num = round($num, $this->numberPrecision);
838 }
839 return $num . $unit;
840 case 'string':
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);
846 }
847 }
848 return $delim . implode($content) . $delim;
849 case 'color':
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;
855 $r = round($r);
856 $g = round($g);
857 $b = round($b);
858
859 if (count($value) == 5 && $value[4] != 1) { // rgba
860 return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
861 }
862
863 $h = sprintf("#%02x%02x%02x", $r, $g, $b);
864
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];
869 }
870 }
871
872 return $h;
873
874 case 'function':
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]");
879 }
880 }
881
882 protected function lib_pow($args) {
883 list($base, $exp) = $this->assertArgs($args, 2, "pow");
884 return pow($this->assertNumber($base), $this->assertNumber($exp));
885 }
886
887 protected function lib_pi() {
888 return pi();
889 }
890
891 protected function lib_mod($args) {
892 list($a, $b) = $this->assertArgs($args, 2, "mod");
893 return $this->assertNumber($a) % $this->assertNumber($b);
894 }
895
896 protected function lib_tan($num) {
897 return tan($this->assertNumber($num));
898 }
899
900 protected function lib_sin($num) {
901 return sin($this->assertNumber($num));
902 }
903
904 protected function lib_cos($num) {
905 return cos($this->assertNumber($num));
906 }
907
908 protected function lib_atan($num) {
909 $num = atan($this->assertNumber($num));
910 return array("number", $num, "rad");
911 }
912
913 protected function lib_asin($num) {
914 $num = asin($this->assertNumber($num));
915 return array("number", $num, "rad");
916 }
917
918 protected function lib_acos($num) {
919 $num = acos($this->assertNumber($num));
920 return array("number", $num, "rad");
921 }
922
923 protected function lib_sqrt($num) {
924 return sqrt($this->assertNumber($num));
925 }
926
927 protected function lib_extract($value) {
928 list($list, $idx) = $this->assertArgs($value, 2, "extract");
929 $idx = $this->assertNumber($idx);
930 // 1 indexed
931 if ($list[0] == "list" && isset($list[2][$idx - 1])) {
932 return $list[2][$idx - 1];
933 }
934 }
935
936 protected function lib_isnumber($value) {
937 return $this->toBool($value[0] == "number");
938 }
939
940 protected function lib_isstring($value) {
941 return $this->toBool($value[0] == "string");
942 }
943
944 protected function lib_iscolor($value) {
945 return $this->toBool($this->coerceColor($value));
946 }
947
948 protected function lib_iskeyword($value) {
949 return $this->toBool($value[0] == "keyword");
950 }
951
952 protected function lib_ispixel($value) {
953 return $this->toBool($value[0] == "number" && $value[2] == "px");
954 }
955
956 protected function lib_ispercentage($value) {
957 return $this->toBool($value[0] == "number" && $value[2] == "%");
958 }
959
960 protected function lib_isem($value) {
961 return $this->toBool($value[0] == "number" && $value[2] == "em");
962 }
963
964 protected function lib_isrem($value) {
965 return $this->toBool($value[0] == "number" && $value[2] == "rem");
966 }
967
968 protected function lib_rgbahex($color) {
969 $color = $this->coerceColor($color);
970 if (is_null($color))
971 $this->throwError("color expected for rgbahex");
972
973 return sprintf("#%02x%02x%02x%02x",
974 isset($color[4]) ? $color[4]*255 : 255,
975 $color[1],$color[2], $color[3]);
976 }
977
978 protected function lib_argb($color){
979 return $this->lib_rgbahex($color);
980 }
981
982 // utility func to unquote a string
983 protected function lib_e($arg) {
984 switch ($arg[0]) {
985 case "list":
986 $items = $arg[2];
987 if (isset($items[0])) {
988 return $this->lib_e($items[0]);
989 }
990 return self::$defaultValue;
991 case "string":
992 $arg[1] = "";
993 return $arg;
994 case "keyword":
995 return $arg;
996 default:
997 return array("keyword", $this->compileValue($arg));
998 }
999 }
1000
1001 protected function lib__sprintf($args) {
1002 if ($args[0] != "list") return $args;
1003 $values = $args[2];
1004 $string = array_shift($values);
1005 $template = $this->compileValue($this->lib_e($string));
1006
1007 $i = 0;
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', '');
1012
1013 // lessjs compat, renders fully expanded color, not raw color
1014 if ($color = $this->coerceColor($val)) {
1015 $val = $color;
1016 }
1017
1018 $i++;
1019 $rep = $this->compileValue($this->lib_e($val));
1020 $template = preg_replace('/'.self::preg_quote($match).'/',
1021 $rep, $template, 1);
1022 }
1023 }
1024
1025 $d = $string[0] == "string" ? $string[1] : '"';
1026 return array("string", $d, array($template));
1027 }
1028
1029 protected function lib_floor($arg) {
1030 $value = $this->assertNumber($arg);
1031 return array("number", floor($value), $arg[2]);
1032 }
1033
1034 protected function lib_ceil($arg) {
1035 $value = $this->assertNumber($arg);
1036 return array("number", ceil($value), $arg[2]);
1037 }
1038
1039 protected function lib_round($arg) {
1040 if($arg[0] != "list") {
1041 $value = $this->assertNumber($arg);
1042 return array("number", round($value), $arg[2]);
1043 } else {
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]);
1047 }
1048 }
1049
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)));
1055 } else {
1056 return array("number", $this->assertNumber($arg), "");
1057 }
1058 }
1059
1060 /**
1061 * Helper function to get arguments for color manipulation functions.
1062 * takes a list that contains a color like thing and a percentage
1063 */
1064 protected function colorArgs($args) {
1065 if ($args[0] != 'list' || count($args[2]) < 2) {
1066 return array(array('color', 0, 0, 0), 0);
1067 }
1068 list($color, $delta) = $args[2];
1069 $color = $this->assertColor($color);
1070 $delta = floatval($delta[1]);
1071
1072 return array($color, $delta);
1073 }
1074
1075 protected function lib_darken($args) {
1076 list($color, $delta) = $this->colorArgs($args);
1077
1078 $hsl = $this->toHSL($color);
1079 $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
1080 return $this->toRGB($hsl);
1081 }
1082
1083 protected function lib_lighten($args) {
1084 list($color, $delta) = $this->colorArgs($args);
1085
1086 $hsl = $this->toHSL($color);
1087 $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
1088 return $this->toRGB($hsl);
1089 }
1090
1091 protected function lib_saturate($args) {
1092 list($color, $delta) = $this->colorArgs($args);
1093
1094 $hsl = $this->toHSL($color);
1095 $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
1096 return $this->toRGB($hsl);
1097 }
1098
1099 protected function lib_desaturate($args) {
1100 list($color, $delta) = $this->colorArgs($args);
1101
1102 $hsl = $this->toHSL($color);
1103 $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
1104 return $this->toRGB($hsl);
1105 }
1106
1107 protected function lib_spin($args) {
1108 list($color, $delta) = $this->colorArgs($args);
1109
1110 $hsl = $this->toHSL($color);
1111
1112 $hsl[1] = $hsl[1] + $delta % 360;
1113 if ($hsl[1] < 0) $hsl[1] += 360;
1114
1115 return $this->toRGB($hsl);
1116 }
1117
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);
1121 return $color;
1122 }
1123
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);
1127 return $color;
1128 }
1129
1130 protected function lib_hue($color) {
1131 $hsl = $this->toHSL($this->assertColor($color));
1132 return round($hsl[1]);
1133 }
1134
1135 protected function lib_saturation($color) {
1136 $hsl = $this->toHSL($this->assertColor($color));
1137 return round($hsl[2]);
1138 }
1139
1140 protected function lib_lightness($color) {
1141 $hsl = $this->toHSL($this->assertColor($color));
1142 return round($hsl[3]);
1143 }
1144
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;
1150 }
1151 }
1152
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);
1157 return $color;
1158 }
1159
1160 protected function lib_percentage($arg) {
1161 $num = $this->assertNumber($arg);
1162 return array("number", $num*100, "%");
1163 }
1164
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)");
1171
1172 list($first, $second) = $args[2];
1173 $first = $this->assertColor($first);
1174 $second = $this->assertColor($second);
1175
1176 $first_a = $this->lib_alpha($first);
1177 $second_a = $this->lib_alpha($second);
1178
1179 if (isset($args[2][2])) {
1180 $weight = $args[2][2][1] / 100.0;
1181 } else {
1182 $weight = 0.5;
1183 }
1184
1185 $w = $weight * 2 - 1;
1186 $a = $first_a - $second_a;
1187
1188 $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
1189 $w2 = 1.0 - $w1;
1190
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],
1195 );
1196
1197 if ($first_a != 1.0 || $second_a != 1.0) {
1198 $new[] = $first_a * $weight + $second_a * ($weight - 1);
1199 }
1200
1201 return $this->fixColor($new);
1202 }
1203
1204 protected function lib_contrast($args) {
1205 if ($args[0] != 'list' || count($args[2]) < 3) {
1206 return array(array('color', 0, 0, 0), 0);
1207 }
1208
1209 list($inputColor, $darkColor, $lightColor) = $args[2];
1210
1211 $inputColor = $this->assertColor($inputColor);
1212 $darkColor = $this->assertColor($darkColor);
1213 $lightColor = $this->assertColor($lightColor);
1214 $hsl = $this->toHSL($inputColor);
1215
1216 if ($hsl[3] > 50) {
1217 return $darkColor;
1218 }
1219
1220 return $lightColor;
1221 }
1222
1223 protected function assertColor($value, $error = "expected color value") {
1224 $color = $this->coerceColor($value);
1225 if (is_null($color)) $this->throwError($error);
1226 return $color;
1227 }
1228
1229 protected function assertNumber($value, $error = "expecting number") {
1230 if ($value[0] == "number") return $value[1];
1231 $this->throwError($error);
1232 }
1233
1234 protected function assertArgs($value, $expectedArgs, $name="") {
1235 if ($expectedArgs == 1) {
1236 return $value;
1237 } else {
1238 if ($value[0] !== "list" || $value[1] != ",") $this->throwError("expecting list");
1239 $values = $value[2];
1240 $numValues = count($values);
1241 if ($expectedArgs != $numValues) {
1242 if ($name) {
1243 $name = $name . ": ";
1244 }
1245
1246 $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
1247 }
1248
1249 return $values;
1250 }
1251 }
1252
1253 protected function toHSL($color) {
1254 if ($color[0] == 'hsl') return $color;
1255
1256 $r = $color[1] / 255;
1257 $g = $color[2] / 255;
1258 $b = $color[3] / 255;
1259
1260 $min = min($r, $g, $b);
1261 $max = max($r, $g, $b);
1262
1263 $L = ($min + $max) / 2;
1264 if ($min == $max) {
1265 $S = $H = 0;
1266 } else {
1267 if ($L < 0.5)
1268 $S = ($max - $min)/($max + $min);
1269 else
1270 $S = ($max - $min)/(2.0 - $max - $min);
1271
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);
1275
1276 }
1277
1278 $out = array('hsl',
1279 ($H < 0 ? $H + 6 : $H)*60,
1280 $S*100,
1281 $L*100,
1282 );
1283
1284 if (count($color) > 4) $out[] = $color[4]; // copy alpha
1285 return $out;
1286 }
1287
1288 protected function toRGB_helper($comp, $temp1, $temp2) {
1289 if ($comp < 0) $comp += 1.0;
1290 elseif ($comp > 1) $comp -= 1.0;
1291
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;
1295
1296 return $temp1;
1297 }
1298
1299 /**
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
1302 */
1303 protected function toRGB($color) {
1304 if ($color[0] == 'color') return $color;
1305
1306 $H = $color[1] / 360;
1307 $S = $color[2] / 100;
1308 $L = $color[3] / 100;
1309
1310 if ($S == 0) {
1311 $r = $g = $b = $L;
1312 } else {
1313 $temp2 = $L < 0.5 ?
1314 $L*(1.0 + $S) :
1315 $L + $S - $L * $S;
1316
1317 $temp1 = 2.0 * $L - $temp2;
1318
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);
1322 }
1323
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
1327 return $out;
1328 }
1329
1330 protected function clamp($v, $max = 1, $min = 0) {
1331 return min($max, max($min, $v));
1332 }
1333
1334 /**
1335 * Convert the rgb, rgba, hsl color literals of function type
1336 * as returned by the parser into values of color type.
1337 */
1338 protected function funcToColor($func) {
1339 $fname = $func[1];
1340 if ($func[2][0] != 'list') return false; // need a list of arguments
1341 $rawComponents = $func[2][2];
1342
1343 if ($fname == 'hsl' || $fname == 'hsla') {
1344 $hsl = array('hsl');
1345 $i = 0;
1346 foreach ($rawComponents as $c) {
1347 $val = $this->reduce($c);
1348 $val = isset($val[1]) ? floatval($val[1]) : 0;
1349
1350 if ($i == 0) $clamp = 360;
1351 elseif ($i < 3) $clamp = 100;
1352 else $clamp = 1;
1353
1354 $hsl[] = $this->clamp($val, $clamp);
1355 $i++;
1356 }
1357
1358 while (count($hsl) < 4) $hsl[] = 0;
1359 return $this->toRGB($hsl);
1360
1361 } elseif ($fname == 'rgb' || $fname == 'rgba') {
1362 $components = array();
1363 $i = 1;
1364 foreach ($rawComponents as $c) {
1365 $c = $this->reduce($c);
1366 if ($i < 4) {
1367 if ($c[0] == "number" && $c[2] == "%") {
1368 $components[] = 255 * ($c[1] / 100);
1369 } else {
1370 $components[] = floatval($c[1]);
1371 }
1372 } elseif ($i == 4) {
1373 if ($c[0] == "number" && $c[2] == "%") {
1374 $components[] = 1.0 * ($c[1] / 100);
1375 } else {
1376 $components[] = floatval($c[1]);
1377 }
1378 } else break;
1379
1380 $i++;
1381 }
1382 while (count($components) < 3) $components[] = 0;
1383 array_unshift($components, 'color');
1384 return $this->fixColor($components);
1385 }
1386
1387 return false;
1388 }
1389
1390 protected function reduce($value, $forExpression = false) {
1391 switch ($value[0]) {
1392 case "interpolate":
1393 $reduced = $this->reduce($value[1]);
1394 $var = $this->compileValue($reduced);
1395 $res = $this->reduce(array("variable", $this->vPrefix . $var));
1396
1397 if ($res[0] == "raw_color") {
1398 $res = $this->coerceColor($res);
1399 }
1400
1401 if (empty($value[2])) $res = $this->lib_e($res);
1402
1403 return $res;
1404 case "variable":
1405 $key = $value[1];
1406 if (is_array($key)) {
1407 $key = $this->reduce($key);
1408 $key = $this->vPrefix . $this->compileValue($this->lib_e($key));
1409 }
1410
1411 $seen =& $this->env->seenNames;
1412
1413 if (!empty($seen[$key])) {
1414 $this->throwError("infinite loop detected: $key");
1415 }
1416
1417 $seen[$key] = true;
1418 $out = $this->reduce($this->get($key, self::$defaultValue));
1419 $seen[$key] = false;
1420 return $out;
1421 case "list":
1422 foreach ($value[2] as &$item) {
1423 $item = $this->reduce($item, $forExpression);
1424 }
1425 return $value;
1426 case "expression":
1427 return $this->evaluate($value);
1428 case "string":
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);
1434 }
1435 }
1436 return $value;
1437 case "escape":
1438 list(,$inner) = $value;
1439 return $this->lib_e($this->reduce($inner));
1440 case "function":
1441 $color = $this->funcToColor($value);
1442 if ($color) return $color;
1443
1444 list(, $name, $args) = $value;
1445 if ($name == "%") $name = "_sprintf";
1446 $f = isset($this->libFunctions[$name]) ?
1447 $this->libFunctions[$name] : array($this, 'lib_'.$name);
1448
1449 if (is_callable($f)) {
1450 if ($args[0] == 'list')
1451 $args = self::compressList($args[2], $args[1]);
1452
1453 $ret = call_user_func($f, $this->reduce($args, true), $this);
1454
1455 if (is_null($ret)) {
1456 return array("string", "", array(
1457 $name, "(", $args, ")"
1458 ));
1459 }
1460
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);
1464
1465 return $ret;
1466 }
1467
1468 // plain function, reduce args
1469 $value[2] = $this->reduce($value[2]);
1470 return $value;
1471 case "unary":
1472 list(, $op, $exp) = $value;
1473 $exp = $this->reduce($exp);
1474
1475 if ($exp[0] == "number") {
1476 switch ($op) {
1477 case "+":
1478 return $exp;
1479 case "-":
1480 $exp[1] *= -1;
1481 return $exp;
1482 }
1483 }
1484 return array("string", "", array($op, $exp));
1485 }
1486
1487 if ($forExpression) {
1488 switch ($value[0]) {
1489 case "keyword":
1490 if ($color = $this->coerceColor($value)) {
1491 return $color;
1492 }
1493 break;
1494 case "raw_color":
1495 return $this->coerceColor($value);
1496 }
1497 }
1498
1499 return $value;
1500 }
1501
1502
1503 // coerce a value for use in color operation
1504 protected function coerceColor($value) {
1505 switch($value[0]) {
1506 case 'color': return $value;
1507 case 'raw_color':
1508 $c = array("color", 0, 0, 0);
1509 $colorStr = substr($value[1], 1);
1510 $num = hexdec($colorStr);
1511 $width = strlen($colorStr) == 3 ? 16 : 256;
1512
1513 for ($i = 3; $i > 0; $i--) { // 3 2 1
1514 $t = $num % $width;
1515 $num /= $width;
1516
1517 $c[$i] = $t * (256/$width) + $t * floor(16/$width);
1518 }
1519
1520 return $c;
1521 case 'keyword':
1522 $name = $value[1];
1523 if (isset(self::$cssColors[$name])) {
1524 $rgba = explode(',', self::$cssColors[$name]);
1525
1526 if(isset($rgba[3]))
1527 return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1528
1529 return array('color', $rgba[0], $rgba[1], $rgba[2]);
1530 }
1531 return null;
1532 }
1533 }
1534
1535 // make something string like into a string
1536 protected function coerceString($value) {
1537 switch ($value[0]) {
1538 case "string":
1539 return $value;
1540 case "keyword":
1541 return array("string", "", array($value[1]));
1542 }
1543 return null;
1544 }
1545
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]);
1550 }
1551 return $value;
1552 }
1553
1554 protected function toBool($a) {
1555 if ($a) return self::$TRUE;
1556 else return self::$FALSE;
1557 }
1558
1559 // evaluate an expression
1560 protected function evaluate($exp) {
1561 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1562
1563 $left = $this->reduce($left, true);
1564 $right = $this->reduce($right, true);
1565
1566 if ($leftColor = $this->coerceColor($left)) {
1567 $left = $leftColor;
1568 }
1569
1570 if ($rightColor = $this->coerceColor($right)) {
1571 $right = $rightColor;
1572 }
1573
1574 $ltype = $left[0];
1575 $rtype = $right[0];
1576
1577 // operators that work on all types
1578 if ($op == "and") {
1579 return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
1580 }
1581
1582 if ($op == "=") {
1583 return $this->toBool($this->eq($left, $right) );
1584 }
1585
1586 if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1587 return $str;
1588 }
1589
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;
1595 }
1596
1597 // make the expression look it did before being parsed
1598 $paddedOp = $op;
1599 if ($whiteBefore) $paddedOp = " " . $paddedOp;
1600 if ($whiteAfter) $paddedOp .= " ";
1601
1602 return array("string", "", array($left, $paddedOp, $right));
1603 }
1604
1605 protected function stringConcatenate($left, $right) {
1606 if ($strLeft = $this->coerceString($left)) {
1607 if ($right[0] == "string") {
1608 $right[1] = "";
1609 }
1610 $strLeft[2][] = $right;
1611 return $strLeft;
1612 }
1613
1614 if ($strRight = $this->coerceString($right)) {
1615 array_unshift($strRight[2], $left);
1616 return $strRight;
1617 }
1618 }
1619
1620
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;
1626 }
1627
1628 return $c;
1629 }
1630
1631 protected function op_number_color($op, $lft, $rgt) {
1632 if ($op == '+' || $op == '*') {
1633 return $this->op_color_number($op, $rgt, $lft);
1634 }
1635 }
1636
1637 protected function op_color_number($op, $lft, $rgt) {
1638 if ($rgt[0] == '%') $rgt[1] /= 100;
1639
1640 return $this->op_color_color($op, $lft,
1641 array_fill(1, count($lft) - 1, $rgt[1]));
1642 }
1643
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;
1650 switch ($op) {
1651 case '+':
1652 $out[] = $lval + $rval;
1653 break;
1654 case '-':
1655 $out[] = $lval - $rval;
1656 break;
1657 case '*':
1658 $out[] = $lval * $rval;
1659 break;
1660 case '%':
1661 $out[] = $lval % $rval;
1662 break;
1663 case '/':
1664 if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
1665 $out[] = $lval / $rval;
1666 break;
1667 default:
1668 $this->throwError('evaluate error: color op number failed on op '.$op);
1669 }
1670 }
1671 return $this->fixColor($out);
1672 }
1673
1674 function lib_red($color){
1675 $color = $this->coerceColor($color);
1676 if (is_null($color)) {
1677 $this->throwError('color expected for red()');
1678 }
1679
1680 return $color[1];
1681 }
1682
1683 function lib_green($color){
1684 $color = $this->coerceColor($color);
1685 if (is_null($color)) {
1686 $this->throwError('color expected for green()');
1687 }
1688
1689 return $color[2];
1690 }
1691
1692 function lib_blue($color){
1693 $color = $this->coerceColor($color);
1694 if (is_null($color)) {
1695 $this->throwError('color expected for blue()');
1696 }
1697
1698 return $color[3];
1699 }
1700
1701
1702 // operator on two numbers
1703 protected function op_number_number($op, $left, $right) {
1704 $unit = empty($left[2]) ? $right[2] : $left[2];
1705
1706 $value = 0;
1707 switch ($op) {
1708 case '+':
1709 $value = $left[1] + $right[1];
1710 break;
1711 case '*':
1712 $value = $left[1] * $right[1];
1713 break;
1714 case '-':
1715 $value = $left[1] - $right[1];
1716 break;
1717 case '%':
1718 $value = $left[1] % $right[1];
1719 break;
1720 case '/':
1721 if ($right[1] == 0) $this->throwError('parse error: divide by zero');
1722 $value = $left[1] / $right[1];
1723 break;
1724 case '<':
1725 return $this->toBool($left[1] < $right[1]);
1726 case '>':
1727 return $this->toBool($left[1] > $right[1]);
1728 case '>=':
1729 return $this->toBool($left[1] >= $right[1]);
1730 case '=<':
1731 return $this->toBool($left[1] <= $right[1]);
1732 default:
1733 $this->throwError('parse error: unknown number operator: '.$op);
1734 }
1735
1736 return array("number", $value, $unit);
1737 }
1738
1739
1740 /* environment functions */
1741
1742 protected function makeOutputBlock($type, $selectors = null) {
1743 $b = new stdclass;
1744 $b->lines = array();
1745 $b->children = array();
1746 $b->selectors = $selectors;
1747 $b->type = $type;
1748 $b->parent = $this->scope;
1749 return $b;
1750 }
1751
1752 // the state of execution
1753 protected function pushEnv($block = null) {
1754 $e = new stdclass;
1755 $e->parent = $this->env;
1756 $e->store = array();
1757 $e->block = $block;
1758
1759 $this->env = $e;
1760 return $e;
1761 }
1762
1763 // pop something off the stack
1764 protected function popEnv() {
1765 $old = $this->env;
1766 $this->env = $this->env->parent;
1767 return $old;
1768 }
1769
1770 // set something in the current env
1771 protected function set($name, $value) {
1772 $this->env->store[$name] = $value;
1773 }
1774
1775
1776 // get the highest occurrence entry for a name
1777 protected function get($name, $default=null) {
1778 $current = $this->env;
1779
1780 $isArguments = $name == $this->vPrefix . 'arguments';
1781 while ($current) {
1782 if ($isArguments && isset($current->arguments)) {
1783 return array('list', ' ', $current->arguments);
1784 }
1785
1786 if (isset($current->store[$name]))
1787 return $current->store[$name];
1788 else {
1789 $current = isset($current->storeParent) ?
1790 $current->storeParent : $current->parent;
1791 }
1792 }
1793
1794 return $default;
1795 }
1796
1797 // inject array of unparsed strings into environment as variables
1798 protected function injectVariables($args) {
1799 $this->pushEnv();
1800 $parser = new lessc_parser($this, __METHOD__);
1801 foreach ($args as $name => $strValue) {
1802 if ($name{0} != '@') $name = '@'.$name;
1803 $parser->count = 0;
1804 $parser->buffer = (string)$strValue;
1805 if (!$parser->propertyValue($value)) {
1806 throw new Exception("failed to parse passed in variable $name: $strValue");
1807 }
1808
1809 $this->set($name, $value);
1810 }
1811 }
1812
1813 /**
1814 * Initialize any static state, can initialize parser for a file
1815 * $opts isn't used yet
1816 */
1817 public function __construct($fname = null) {
1818 if ($fname !== null) {
1819 // used for deprecated parse method
1820 $this->_parseFile = $fname;
1821 }
1822 }
1823
1824 public function compile($string, $name = null) {
1825 $locale = setlocale(LC_NUMERIC, 0);
1826 setlocale(LC_NUMERIC, "C");
1827
1828 $this->parser = $this->makeParser($name);
1829 $root = $this->parser->parse($string);
1830
1831 $this->env = null;
1832 $this->scope = null;
1833
1834 $this->formatter = $this->newFormatter();
1835
1836 if (!empty($this->registeredVars)) {
1837 $this->injectVariables($this->registeredVars);
1838 }
1839
1840 $this->sourceParser = $this->parser; // used for error messages
1841 $this->compileBlock($root);
1842
1843 ob_start();
1844 $this->formatter->block($this->scope);
1845 $out = ob_get_clean();
1846 setlocale(LC_NUMERIC, $locale);
1847 return $out;
1848 }
1849
1850 public function compileFile($fname, $outFname = null) {
1851 if (!is_readable($fname)) {
1852 throw new Exception('load error: failed to find '.$fname);
1853 }
1854
1855 $pi = pathinfo($fname);
1856
1857 $oldImport = $this->importDir;
1858
1859 $this->importDir = (array)$this->importDir;
1860 $this->importDir[] = $pi['dirname'].'/';
1861
1862 $this->addParsedFile($fname);
1863
1864 $out = $this->compile(file_get_contents($fname), $fname);
1865
1866 $this->importDir = $oldImport;
1867
1868 if ($outFname !== null) {
1869 return file_put_contents($outFname, $out);
1870 }
1871
1872 return $out;
1873 }
1874
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);
1879 return true;
1880 }
1881 return false;
1882 }
1883
1884 /**
1885 * Execute lessphp on a .less file or a lessphp cache structure
1886 *
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.
1890 *
1891 * The cache structure contains two important keys that may be used
1892 * externally:
1893 *
1894 * compiled: The final compiled CSS
1895 * updated: The time (in seconds) the CSS was last compiled
1896 *
1897 * The cache structure is a plain-ol' PHP associative array and can
1898 * be serialized and unserialized without a hitch.
1899 *
1900 * @param mixed $in Input
1901 * @param bool $force Force rebuild?
1902 * @return array lessphp cache structure
1903 */
1904 public function cachedCompile($in, $force = false) {
1905 // assume no root
1906 $root = null;
1907
1908 if (is_string($in)) {
1909 $root = $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'];
1922 break;
1923 }
1924 }
1925 }
1926 } else {
1927 // TODO: Throw an exception? We got neither a string nor something
1928 // that looks like a compatible lessphp cache structure.
1929 return null;
1930 }
1931
1932 if ($root !== null) {
1933 // If we have a root value which means we should rebuild.
1934 $out = array();
1935 $out['root'] = $root;
1936 $out['compiled'] = $this->compileFile($root);
1937 $out['files'] = $this->allParsedFiles();
1938 $out['updated'] = time();
1939 return $out;
1940 } else {
1941 // No changes, pass back the structure
1942 // we were given initially.
1943 return $in;
1944 }
1945
1946 }
1947
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;
1953 $str = null;
1954 }
1955
1956 $oldVars = $this->registeredVars;
1957 if ($initialVariables !== null) {
1958 $this->setVariables($initialVariables);
1959 }
1960
1961 if ($str == null) {
1962 if (empty($this->_parseFile)) {
1963 throw new exception("nothing to parse");
1964 }
1965
1966 $out = $this->compileFile($this->_parseFile);
1967 } else {
1968 $out = $this->compile($str);
1969 }
1970
1971 $this->registeredVars = $oldVars;
1972 return $out;
1973 }
1974
1975 protected function makeParser($name) {
1976 $parser = new lessc_parser($this, $name);
1977 $parser->writeComments = $this->preserveComments;
1978
1979 return $parser;
1980 }
1981
1982 public function setFormatter($name) {
1983 $this->formatterName = $name;
1984 }
1985
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";
1992 }
1993
1994 return new $className;
1995 }
1996
1997 public function setPreserveComments($preserve) {
1998 $this->preserveComments = $preserve;
1999 }
2000
2001 public function registerFunction($name, $func) {
2002 $this->libFunctions[$name] = $func;
2003 }
2004
2005 public function unregisterFunction($name) {
2006 unset($this->libFunctions[$name]);
2007 }
2008
2009 public function setVariables($variables) {
2010 $this->registeredVars = array_merge($this->registeredVars, $variables);
2011 }
2012
2013 public function unsetVariable($name) {
2014 unset($this->registeredVars[$name]);
2015 }
2016
2017 public function setImportDir($dirs) {
2018 $this->importDir = (array)$dirs;
2019 }
2020
2021 public function addImportDir($dir) {
2022 $this->importDir = (array)$this->importDir;
2023 $this->importDir[] = $dir;
2024 }
2025
2026 public function allParsedFiles() {
2027 return $this->allParsedFiles;
2028 }
2029
2030 protected function addParsedFile($file) {
2031 $this->allParsedFiles[realpath($file)] = filemtime($file);
2032 }
2033
2034 /**
2035 * Uses the current value of $this->count to show line and line number
2036 */
2037 protected function throwError($msg = null) {
2038 if ($this->sourceLoc >= 0) {
2039 $this->sourceParser->throwError($msg, $this->sourceLoc);
2040 }
2041 throw new exception($msg);
2042 }
2043
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) {
2048 $less = new self;
2049 }
2050 return $less->checkedCompile($in, $out);
2051 }
2052
2053 public static function cexecute($in, $force = false, $less = null) {
2054 if ($less === null) {
2055 $less = new self;
2056 }
2057 return $less->cachedCompile($in, $force);
2058 }
2059
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',
2068 'black' => '0,0,0',
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',
2180 'red' => '255,0,0',
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'
2209 );
2210 }
2211
2212 // responsible for taking a string of LESS code and converting it into a
2213 // syntax tree
2214 class lessc_parser {
2215 static protected $nextBlockId = 0; // used to uniquely identify blocks
2216
2217 static protected $precedence = array(
2218 '=<' => 0,
2219 '>=' => 0,
2220 '=' => 0,
2221 '<' => 0,
2222 '>' => 0,
2223
2224 '+' => 1,
2225 '-' => 1,
2226 '*' => 2,
2227 '/' => 2,
2228 '%' => 2,
2229 );
2230
2231 static protected $whitePattern;
2232 static protected $commentMulti;
2233
2234 static protected $commentSingle = "//";
2235 static protected $commentMultiLeft = "/*";
2236 static protected $commentMultiRight = "*/";
2237
2238 // regex string to match any of the operators
2239 static protected $operatorString;
2240
2241 // these properties will supress division unless it's inside parenthases
2242 static protected $supressDivisionProps =
2243 array('/border-radius$/i', '/^font$/i');
2244
2245 protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
2246 protected $lineDirectives = array("charset");
2247
2248 /**
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
2251 * ambiguous.
2252 *
2253 * Consider:
2254 * property1: 10 -5; // is two numbers, 10 and -5
2255 * property2: (10 -5); // should evaluate to 5
2256 */
2257 protected $inParens = false;
2258
2259 // caches preg escaped literals
2260 static protected $literalCache = array();
2261
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;
2266
2267 $this->sourceName = $sourceName; // name used for error messages
2268
2269 $this->writeComments = false;
2270
2271 if (!self::$operatorString) {
2272 self::$operatorString =
2273 '('.implode('|', array_map(array('lessc', 'preg_quote'),
2274 array_keys(self::$precedence))).')';
2275
2276 $commentSingle = lessc::preg_quote(self::$commentSingle);
2277 $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
2278 $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
2279
2280 self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
2281 self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
2282 }
2283 }
2284
2285 public function parse($buffer) {
2286 $this->count = 0;
2287 $this->line = 1;
2288
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();
2294
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);
2299 // }
2300 $this->whitespace();
2301
2302 // parse the entire file
2303 $lastCount = $this->count;
2304 while (false !== $this->parseChunk());
2305
2306 if ($this->count != strlen($this->buffer))
2307 $this->throwError();
2308
2309 // TODO report where the block was opened
2310 if (!is_null($this->env->parent))
2311 throw new exception('parse error: unclosed block');
2312
2313 return $this->env;
2314 }
2315
2316 /**
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.
2320 *
2321 * This function is called repeatedly until the entire document is
2322 * parsed.
2323 *
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.
2327 *
2328 * Consider the function lessc::keyword(). (all parse functions are
2329 * structured the same)
2330 *
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.
2336 *
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.
2340 *
2341 * Because of the format of the functions, to parse an entire string of
2342 * grammatical rules, you can chain them together using &&.
2343 *
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.
2347 *
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.
2351 */
2352 protected function parseChunk() {
2353 if (empty($this->buffer)) return false;
2354 $s = $this->seek();
2355
2356 // setting a property
2357 if ($this->keyword($key) && $this->assign() &&
2358 $this->propertyValue($value, $key) && $this->end())
2359 {
2360 $this->append(array('assign', $key, $value), $s);
2361 return true;
2362 } else {
2363 $this->seek($s);
2364 }
2365
2366
2367 // look for special css blocks
2368 if ($this->literal('@', false)) {
2369 $this->count--;
2370
2371 // media
2372 if ($this->literal('@media')) {
2373 if (($this->mediaQueryList($mediaQueries) || true)
2374 && $this->literal('{'))
2375 {
2376 $media = $this->pushSpecialBlock("media");
2377 $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
2378 return true;
2379 } else {
2380 $this->seek($s);
2381 return false;
2382 }
2383 }
2384
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("{"))
2389 {
2390 $dir = $this->pushSpecialBlock("directive");
2391 $dir->name = $dirName;
2392 if (isset($dirValue)) $dir->value = $dirValue;
2393 return true;
2394 }
2395 } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
2396 if ($this->propertyValue($dirValue) && $this->end()) {
2397 $this->append(array("directive", $dirName, $dirValue));
2398 return true;
2399 }
2400 }
2401 }
2402
2403 $this->seek($s);
2404 }
2405
2406 // setting a variable
2407 if ($this->variable($var) && $this->assign() &&
2408 $this->propertyValue($value) && $this->end())
2409 {
2410 $this->append(array('assign', $var, $value), $s);
2411 return true;
2412 } else {
2413 $this->seek($s);
2414 }
2415
2416 if ($this->import($importValue)) {
2417 $this->append($importValue, $s);
2418 return true;
2419 }
2420
2421 // opening parametric mixin
2422 if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
2423 ($this->guards($guards) || true) &&
2424 $this->literal('{'))
2425 {
2426 $block = $this->pushBlock($this->fixTags(array($tag)));
2427 $block->args = $args;
2428 $block->isVararg = $isVararg;
2429 if (!empty($guards)) $block->guards = $guards;
2430 return true;
2431 } else {
2432 $this->seek($s);
2433 }
2434
2435 // opening a simple block
2436 if ($this->tags($tags) && $this->literal('{')) {
2437 $tags = $this->fixTags($tags);
2438 $this->pushBlock($tags);
2439 return true;
2440 } else {
2441 $this->seek($s);
2442 }
2443
2444 // closing a block
2445 if ($this->literal('}', false)) {
2446 try {
2447 $block = $this->pop();
2448 } catch (exception $e) {
2449 $this->seek($s);
2450 $this->throwError($e->getMessage());
2451 }
2452
2453 $hidden = false;
2454 if (is_null($block->type)) {
2455 $hidden = true;
2456 if (!isset($block->args)) {
2457 foreach ($block->tags as $tag) {
2458 if (!is_string($tag) || $tag{0} != $this->lessc->mPrefix) {
2459 $hidden = false;
2460 break;
2461 }
2462 }
2463 }
2464
2465 foreach ($block->tags as $tag) {
2466 if (is_string($tag)) {
2467 $this->env->children[$tag][] = $block;
2468 }
2469 }
2470 }
2471
2472 if (!$hidden) {
2473 $this->append(array('block', $block), $s);
2474 }
2475
2476 // this is done here so comments aren't bundled into he block that
2477 // was just closed
2478 $this->whitespace();
2479 return true;
2480 }
2481
2482 // mixin
2483 if ($this->mixinTags($tags) &&
2484 ($this->argumentDef($argv, $isVararg) || true) &&
2485 ($this->keyword($suffix) || true) && $this->end())
2486 {
2487 $tags = $this->fixTags($tags);
2488 $this->append(array('mixin', $tags, $argv, $suffix), $s);
2489 return true;
2490 } else {
2491 $this->seek($s);
2492 }
2493
2494 // spare ;
2495 if ($this->literal(';')) return true;
2496
2497 return false; // got nothing, throw error
2498 }
2499
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';
2505
2506 return preg_match($pattern, $dirname);
2507 }
2508
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;
2514 }
2515 return $tags;
2516 }
2517
2518 // a list of expressions
2519 protected function expressionList(&$exps) {
2520 $values = array();
2521
2522 while ($this->expression($exp)) {
2523 $values[] = $exp;
2524 }
2525
2526 if (count($values) == 0) return false;
2527
2528 $exps = lessc::compressList($values, ' ');
2529 return true;
2530 }
2531
2532 /**
2533 * Attempt to consume an expression.
2534 * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
2535 */
2536 protected function expression(&$out) {
2537 if ($this->value($lhs)) {
2538 $out = $this->expHelper($lhs, 0);
2539
2540 // look for / shorthand
2541 if (!empty($this->env->supressedDivision)) {
2542 unset($this->env->supressedDivision);
2543 $s = $this->seek();
2544 if ($this->literal("/") && $this->value($rhs)) {
2545 $out = array("list", "",
2546 array($out, array("keyword", "/"), $rhs));
2547 } else {
2548 $this->seek($s);
2549 }
2550 }
2551
2552 return true;
2553 }
2554 return false;
2555 }
2556
2557 /**
2558 * recursively parse infix equation with $lhs at precedence $minP
2559 */
2560 protected function expHelper($lhs, $minP) {
2561 $this->inExp = true;
2562 $ss = $this->seek();
2563
2564 while (true) {
2565 $whiteBefore = isset($this->buffer[$this->count - 1]) &&
2566 ctype_space($this->buffer[$this->count - 1]);
2567
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;
2571
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;
2577 break 2;
2578 }
2579 }
2580 }
2581
2582
2583 $whiteAfter = isset($this->buffer[$this->count - 1]) &&
2584 ctype_space($this->buffer[$this->count - 1]);
2585
2586 if (!$this->value($rhs)) break;
2587
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]]);
2591 }
2592
2593 $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
2594 $ss = $this->seek();
2595
2596 continue;
2597 }
2598
2599 break;
2600 }
2601
2602 $this->seek($ss);
2603
2604 return $lhs;
2605 }
2606
2607 // consume a list of values for a property
2608 public function propertyValue(&$value, $keyName = null) {
2609 $values = array();
2610
2611 if ($keyName !== null) $this->env->currentProperty = $keyName;
2612
2613 $s = null;
2614 while ($this->expressionList($v)) {
2615 $values[] = $v;
2616 $s = $this->seek();
2617 if (!$this->literal(',')) break;
2618 }
2619
2620 if ($s) $this->seek($s);
2621
2622 if ($keyName !== null) unset($this->env->currentProperty);
2623
2624 if (count($values) == 0) return false;
2625
2626 $value = lessc::compressList($values, ', ');
2627 return true;
2628 }
2629
2630 protected function parenValue(&$out) {
2631 $s = $this->seek();
2632
2633 // speed shortcut
2634 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
2635 return false;
2636 }
2637
2638 $inParens = $this->inParens;
2639 if ($this->literal("(") &&
2640 ($this->inParens = true) && $this->expression($exp) &&
2641 $this->literal(")"))
2642 {
2643 $out = $exp;
2644 $this->inParens = $inParens;
2645 return true;
2646 } else {
2647 $this->inParens = $inParens;
2648 $this->seek($s);
2649 }
2650
2651 return false;
2652 }
2653
2654 // a single value
2655 protected function value(&$value) {
2656 $s = $this->seek();
2657
2658 // speed shortcut
2659 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
2660 // negation
2661 if ($this->literal("-", false) &&
2662 (($this->variable($inner) && $inner = array("variable", $inner)) ||
2663 $this->unit($inner) ||
2664 $this->parenValue($inner)))
2665 {
2666 $value = array("unary", "-", $inner);
2667 return true;
2668 } else {
2669 $this->seek($s);
2670 }
2671 }
2672
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;
2678
2679 if ($this->keyword($word)) {
2680 $value = array('keyword', $word);
2681 return true;
2682 }
2683
2684 // try a variable
2685 if ($this->variable($var)) {
2686 $value = array('variable', $var);
2687 return true;
2688 }
2689
2690 // unquote string (should this work on any type?
2691 if ($this->literal("~") && $this->string($str)) {
2692 $value = array("escape", $str);
2693 return true;
2694 } else {
2695 $this->seek($s);
2696 }
2697
2698 // css hack: \0
2699 if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
2700 $value = array('keyword', '\\'.$m[1]);
2701 return true;
2702 } else {
2703 $this->seek($s);
2704 }
2705
2706 return false;
2707 }
2708
2709 // an import statement
2710 protected function import(&$out) {
2711 $s = $this->seek();
2712 if (!$this->literal('@import')) return false;
2713
2714 // @import "something.css" media;
2715 // @import url("something.css") media;
2716 // @import url(something.css) media;
2717
2718 if ($this->propertyValue($value)) {
2719 $out = array("import", $value);
2720 return true;
2721 }
2722 }
2723
2724 protected function mediaQueryList(&$out) {
2725 if ($this->genericList($list, "mediaQuery", ",", false)) {
2726 $out = $list[2];
2727 return true;
2728 }
2729 return false;
2730 }
2731
2732 protected function mediaQuery(&$out) {
2733 $s = $this->seek();
2734
2735 $expressions = null;
2736 $parts = array();
2737
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;
2743 $parts[] = $prop;
2744 } else {
2745 $this->seek($s);
2746 }
2747
2748
2749 if (!empty($mediaType) && !$this->literal("and")) {
2750 // ~
2751 } else {
2752 $this->genericList($expressions, "mediaExpression", "and", false);
2753 if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
2754 }
2755
2756 if (count($parts) == 0) {
2757 $this->seek($s);
2758 return false;
2759 }
2760
2761 $out = $parts;
2762 return true;
2763 }
2764
2765 protected function mediaExpression(&$out) {
2766 $s = $this->seek();
2767 $value = null;
2768 if ($this->literal("(") &&
2769 $this->keyword($feature) &&
2770 ($this->literal(":") && $this->expression($value) || true) &&
2771 $this->literal(")"))
2772 {
2773 $out = array("mediaExp", $feature);
2774 if ($value) $out[] = $value;
2775 return true;
2776 } elseif ($this->variable($variable)) {
2777 $out = array('variable', $variable);
2778 return true;
2779 }
2780
2781 $this->seek($s);
2782 return false;
2783 }
2784
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;
2789
2790 $stop = array("'", '"', "@{", $end);
2791 $stop = array_map(array("lessc", "preg_quote"), $stop);
2792 // $stop[] = self::$commentMulti;
2793
2794 if (!is_null($rejectStrs)) {
2795 $stop = array_merge($stop, $rejectStrs);
2796 }
2797
2798 $patt = '(.*?)('.implode("|", $stop).')';
2799
2800 $nestingLevel = 0;
2801
2802 $content = array();
2803 while ($this->match($patt, $m, false)) {
2804 if (!empty($m[1])) {
2805 $content[] = $m[1];
2806 if ($nestingOpen) {
2807 $nestingLevel += substr_count($m[1], $nestingOpen);
2808 }
2809 }
2810
2811 $tok = $m[2];
2812
2813 $this->count-= strlen($tok);
2814 if ($tok == $end) {
2815 if ($nestingLevel == 0) {
2816 break;
2817 } else {
2818 $nestingLevel--;
2819 }
2820 }
2821
2822 if (($tok == "'" || $tok == '"') && $this->string($str)) {
2823 $content[] = $str;
2824 continue;
2825 }
2826
2827 if ($tok == "@{" && $this->interpolation($inter)) {
2828 $content[] = $inter;
2829 continue;
2830 }
2831
2832 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
2833 break;
2834 }
2835
2836 $content[] = $tok;
2837 $this->count+= strlen($tok);
2838 }
2839
2840 $this->eatWhiteDefault = $oldWhite;
2841
2842 if (count($content) == 0) return false;
2843
2844 // trim the end
2845 if (is_string(end($content))) {
2846 $content[count($content) - 1] = rtrim(end($content));
2847 }
2848
2849 $out = array("string", "", $content);
2850 return true;
2851 }
2852
2853 protected function string(&$out) {
2854 $s = $this->seek();
2855 if ($this->literal('"', false)) {
2856 $delim = '"';
2857 } elseif ($this->literal("'", false)) {
2858 $delim = "'";
2859 } else {
2860 return false;
2861 }
2862
2863 $content = array();
2864
2865 // look for either ending delim , escape, or string interpolation
2866 $patt = '([^\n]*?)(@\{|\\\\|' .
2867 lessc::preg_quote($delim).')';
2868
2869 $oldWhite = $this->eatWhiteDefault;
2870 $this->eatWhiteDefault = false;
2871
2872 while ($this->match($patt, $m, false)) {
2873 $content[] = $m[1];
2874 if ($m[2] == "@{") {
2875 $this->count -= strlen($m[2]);
2876 if ($this->interpolation($inter, false)) {
2877 $content[] = $inter;
2878 } else {
2879 $this->count += strlen($m[2]);
2880 $content[] = "@{"; // ignore it
2881 }
2882 } elseif ($m[2] == '\\') {
2883 $content[] = $m[2];
2884 if ($this->literal($delim, false)) {
2885 $content[] = $delim;
2886 }
2887 } else {
2888 $this->count -= strlen($delim);
2889 break; // delim
2890 }
2891 }
2892
2893 $this->eatWhiteDefault = $oldWhite;
2894
2895 if ($this->literal($delim)) {
2896 $out = array("string", $delim, $content);
2897 return true;
2898 }
2899
2900 $this->seek($s);
2901 return false;
2902 }
2903
2904 protected function interpolation(&$out) {
2905 $oldWhite = $this->eatWhiteDefault;
2906 $this->eatWhiteDefault = true;
2907
2908 $s = $this->seek();
2909 if ($this->literal("@{") &&
2910 $this->openString("}", $interp, null, array("'", '"', ";")) &&
2911 $this->literal("}", false))
2912 {
2913 $out = array("interpolate", $interp);
2914 $this->eatWhiteDefault = $oldWhite;
2915 if ($this->eatWhiteDefault) $this->whitespace();
2916 return true;
2917 }
2918
2919 $this->eatWhiteDefault = $oldWhite;
2920 $this->seek($s);
2921 return false;
2922 }
2923
2924 protected function unit(&$unit) {
2925 // speed shortcut
2926 if (isset($this->buffer[$this->count])) {
2927 $char = $this->buffer[$this->count];
2928 if (!ctype_digit($char) && $char != ".") return false;
2929 }
2930
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]);
2933 return true;
2934 }
2935 return false;
2936 }
2937
2938 // a # color
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]));
2943 } else {
2944 $out = array("raw_color", $m[1]);
2945 }
2946 return true;
2947 }
2948
2949 return false;
2950 }
2951
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
2956 // delimiter.
2957 protected function argumentDef(&$args, &$isVararg) {
2958 $s = $this->seek();
2959 if (!$this->literal('(')) return false;
2960
2961 $values = array();
2962 $delim = ",";
2963 $method = "expressionList";
2964
2965 $isVararg = false;
2966 while (true) {
2967 if ($this->literal("...")) {
2968 $isVararg = true;
2969 break;
2970 }
2971
2972 if ($this->$method($value)) {
2973 if ($value[0] == "variable") {
2974 $arg = array("arg", $value[1]);
2975 $ss = $this->seek();
2976
2977 if ($this->assign() && $this->$method($rhs)) {
2978 $arg[] = $rhs;
2979 } else {
2980 $this->seek($ss);
2981 if ($this->literal("...")) {
2982 $arg[0] = "rest";
2983 $isVararg = true;
2984 }
2985 }
2986
2987 $values[] = $arg;
2988 if ($isVararg) break;
2989 continue;
2990 } else {
2991 $values[] = array("lit", $value);
2992 }
2993 }
2994
2995
2996 if (!$this->literal($delim)) {
2997 if ($delim == "," && $this->literal(";")) {
2998 // found new delim, convert existing args
2999 $delim = ";";
3000 $method = "propertyValue";
3001
3002 // transform arg list
3003 if (isset($values[1])) { // 2 items
3004 $newList = array();
3005 foreach ($values as $i => $arg) {
3006 switch($arg[0]) {
3007 case "arg":
3008 if ($i) {
3009 $this->throwError("Cannot mix ; and , as delimiter types");
3010 }
3011 $newList[] = $arg[2];
3012 break;
3013 case "lit":
3014 $newList[] = $arg[1];
3015 break;
3016 case "rest":
3017 $this->throwError("Unexpected rest before semicolon");
3018 }
3019 }
3020
3021 $newList = array("list", ", ", $newList);
3022
3023 switch ($values[0][0]) {
3024 case "arg":
3025 $newArg = array("arg", $values[0][1], $newList);
3026 break;
3027 case "lit":
3028 $newArg = array("lit", $newList);
3029 break;
3030 }
3031
3032 } elseif ($values) { // 1 item
3033 $newArg = $values[0];
3034 }
3035
3036 if ($newArg) {
3037 $values = array($newArg);
3038 }
3039 } else {
3040 break;
3041 }
3042 }
3043 }
3044
3045 if (!$this->literal(')')) {
3046 $this->seek($s);
3047 return false;
3048 }
3049
3050 $args = $values;
3051
3052 return true;
3053 }
3054
3055 // consume a list of tags
3056 // this accepts a hanging delimiter
3057 protected function tags(&$tags, $simple = false, $delim = ',') {
3058 $tags = array();
3059 while ($this->tag($tt, $simple)) {
3060 $tags[] = $tt;
3061 if (!$this->literal($delim)) break;
3062 }
3063 if (count($tags) == 0) return false;
3064
3065 return true;
3066 }
3067
3068 // list of tags of specifying mixin path
3069 // optionally separated by > (lazy, accepts extra >)
3070 protected function mixinTags(&$tags) {
3071 $s = $this->seek();
3072 $tags = array();
3073 while ($this->tag($tt, true)) {
3074 $tags[] = $tt;
3075 $this->literal(">");
3076 }
3077
3078 if (count($tags) == 0) return false;
3079
3080 return true;
3081 }
3082
3083 // a bracketed value (contained within in a tag definition)
3084 protected function tagBracket(&$parts, &$hasExpression) {
3085 // speed shortcut
3086 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
3087 return false;
3088 }
3089
3090 $s = $this->seek();
3091
3092 $hasInterpolation = false;
3093
3094 if ($this->literal("[", false)) {
3095 $attrParts = array("[");
3096 // keyword, string, operator
3097 while (true) {
3098 if ($this->literal("]", false)) {
3099 $this->count--;
3100 break; // get out early
3101 }
3102
3103 if ($this->match('\s+', $m)) {
3104 $attrParts[] = " ";
3105 continue;
3106 }
3107 if ($this->string($str)) {
3108 // escape parent selector, (yuck)
3109 foreach ($str[2] as &$chunk) {
3110 $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
3111 }
3112
3113 $attrParts[] = $str;
3114 $hasInterpolation = true;
3115 continue;
3116 }
3117
3118 if ($this->keyword($word)) {
3119 $attrParts[] = $word;
3120 continue;
3121 }
3122
3123 if ($this->interpolation($inter, false)) {
3124 $attrParts[] = $inter;
3125 $hasInterpolation = true;
3126 continue;
3127 }
3128
3129 // operator, handles attr namespace too
3130 if ($this->match('[|-~\$\*\^=]+', $m)) {
3131 $attrParts[] = $m[0];
3132 continue;
3133 }
3134
3135 break;
3136 }
3137
3138 if ($this->literal("]", false)) {
3139 $attrParts[] = "]";
3140 foreach ($attrParts as $part) {
3141 $parts[] = $part;
3142 }
3143 $hasExpression = $hasExpression || $hasInterpolation;
3144 return true;
3145 }
3146 $this->seek($s);
3147 }
3148
3149 $this->seek($s);
3150 return false;
3151 }
3152
3153 // a space separated list of selectors
3154 protected function tag(&$tag, $simple = false) {
3155 if ($simple)
3156 $chars = '^@,:;{}\][>\(\) "\'';
3157 else
3158 $chars = '^@,;{}["\'';
3159
3160 $s = $this->seek();
3161
3162 $hasExpression = false;
3163 $parts = array();
3164 while ($this->tagBracket($parts, $hasExpression));
3165
3166 $oldWhite = $this->eatWhiteDefault;
3167 $this->eatWhiteDefault = false;
3168
3169 while (true) {
3170 if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
3171 $parts[] = $m[1];
3172 if ($simple) break;
3173
3174 while ($this->tagBracket($parts, $hasExpression));
3175 continue;
3176 }
3177
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
3182 $parts[] = $interp;
3183 continue;
3184 }
3185
3186 if ($this->literal("@")) {
3187 $parts[] = "@";
3188 continue;
3189 }
3190 }
3191
3192 if ($this->unit($unit)) { // for keyframes
3193 $parts[] = $unit[1];
3194 $parts[] = $unit[2];
3195 continue;
3196 }
3197
3198 break;
3199 }
3200
3201 $this->eatWhiteDefault = $oldWhite;
3202 if (!$parts) {
3203 $this->seek($s);
3204 return false;
3205 }
3206
3207 if ($hasExpression) {
3208 $tag = array("exp", array("string", "", $parts));
3209 } else {
3210 $tag = trim(implode($parts));
3211 }
3212
3213 $this->whitespace();
3214 return true;
3215 }
3216
3217 // a css function
3218 protected function func(&$func) {
3219 $s = $this->seek();
3220
3221 if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
3222 $fname = $m[1];
3223
3224 $sPreArgs = $this->seek();
3225
3226 $args = array();
3227 while (true) {
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));
3232 } else {
3233 $this->seek($ss);
3234 if ($this->expressionList($value)) {
3235 $args[] = $value;
3236 }
3237 }
3238
3239 if (!$this->literal(',')) break;
3240 }
3241 $args = array('list', ',', $args);
3242
3243 if ($this->literal(')')) {
3244 $func = array('function', $fname, $args);
3245 return true;
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);
3251 return true;
3252 }
3253 }
3254 }
3255
3256 $this->seek($s);
3257 return false;
3258 }
3259
3260 // consume a less variable
3261 protected function variable(&$name) {
3262 $s = $this->seek();
3263 if ($this->literal($this->lessc->vPrefix, false) &&
3264 ($this->variable($sub) || $this->keyword($name)))
3265 {
3266 if (!empty($sub)) {
3267 $name = array('variable', $sub);
3268 } else {
3269 $name = $this->lessc->vPrefix.$name;
3270 }
3271 return true;
3272 }
3273
3274 $name = null;
3275 $this->seek($s);
3276 return false;
3277 }
3278
3279 /**
3280 * Consume an assignment operator
3281 * Can optionally take a name that will be set to the current property name
3282 */
3283 protected function assign($name = null) {
3284 if ($name) $this->currentProperty = $name;
3285 return $this->literal(':') || $this->literal('=');
3286 }
3287
3288 // consume a keyword
3289 protected function keyword(&$word) {
3290 if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
3291 $word = $m[1];
3292 return true;
3293 }
3294 return false;
3295 }
3296
3297 // consume an end of statement delimiter
3298 protected function end() {
3299 if ($this->literal(';')) {
3300 return true;
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 ;
3303 return true;
3304 }
3305 return false;
3306 }
3307
3308 protected function guards(&$guards) {
3309 $s = $this->seek();
3310
3311 if (!$this->literal("when")) {
3312 $this->seek($s);
3313 return false;
3314 }
3315
3316 $guards = array();
3317
3318 while ($this->guardGroup($g)) {
3319 $guards[] = $g;
3320 if (!$this->literal(",")) break;
3321 }
3322
3323 if (count($guards) == 0) {
3324 $guards = null;
3325 $this->seek($s);
3326 return false;
3327 }
3328
3329 return true;
3330 }
3331
3332 // a bunch of guards that are and'd together
3333 // TODO rename to guardGroup
3334 protected function guardGroup(&$guardGroup) {
3335 $s = $this->seek();
3336 $guardGroup = array();
3337 while ($this->guard($guard)) {
3338 $guardGroup[] = $guard;
3339 if (!$this->literal("and")) break;
3340 }
3341
3342 if (count($guardGroup) == 0) {
3343 $guardGroup = null;
3344 $this->seek($s);
3345 return false;
3346 }
3347
3348 return true;
3349 }
3350
3351 protected function guard(&$guard) {
3352 $s = $this->seek();
3353 $negate = $this->literal("not");
3354
3355 if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
3356 $guard = $exp;
3357 if ($negate) $guard = array("negate", $guard);
3358 return true;
3359 }
3360
3361 $this->seek($s);
3362 return false;
3363 }
3364
3365 /* raw parsing functions */
3366
3367 protected function literal($what, $eatWhitespace = null) {
3368 if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
3369
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) {
3374 $this->count++;
3375 return true;
3376 }
3377 // goes below...
3378 } else {
3379 return false;
3380 }
3381 }
3382
3383 if (!isset(self::$literalCache[$what])) {
3384 self::$literalCache[$what] = lessc::preg_quote($what);
3385 }
3386
3387 return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
3388 }
3389
3390 protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
3391 $s = $this->seek();
3392 $items = array();
3393 while ($this->$parseItem($value)) {
3394 $items[] = $value;
3395 if ($delim) {
3396 if (!$this->literal($delim)) break;
3397 }
3398 }
3399
3400 if (count($items) == 0) {
3401 $this->seek($s);
3402 return false;
3403 }
3404
3405 if ($flatten && count($items) == 1) {
3406 $out = $items[0];
3407 } else {
3408 $out = array("list", $delim, $items);
3409 }
3410
3411 return true;
3412 }
3413
3414
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;
3421 } else {
3422 $validChars = $allowNewline ? "." : "[^\n]";
3423 }
3424 if (!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what), $m, !$until)) return false;
3425 if ($until) $this->count -= strlen($what); // give back $what
3426 $out = $m[1];
3427 return true;
3428 }
3429
3430 // try to match something on head of buffer
3431 protected function match($regex, &$out, $eatWhitespace = null) {
3432 if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
3433
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();
3438 return true;
3439 }
3440 return false;
3441 }
3442
3443 // match some whitespace
3444 protected function whitespace() {
3445 if ($this->writeComments) {
3446 $gotWhite = false;
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;
3451 }
3452 $this->count += strlen($m[0]);
3453 $gotWhite = true;
3454 }
3455 return $gotWhite;
3456 } else {
3457 $this->match("", $m);
3458 return strlen($m[0]) > 0;
3459 }
3460 }
3461
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);
3467
3468 return $result;
3469 }
3470
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;
3475 return true;
3476 }
3477
3478 /* misc functions */
3479
3480 public function throwError($msg = "parse error", $count = null) {
3481 $count = is_null($count) ? $this->count : $count;
3482
3483 $line = $this->line +
3484 substr_count(substr($this->buffer, 0, $count), "\n");
3485
3486 if (!empty($this->sourceName)) {
3487 $loc = "$this->sourceName on line $line";
3488 } else {
3489 $loc = "line: $line";
3490 }
3491
3492 // TODO this depends on $this->count
3493 if ($this->peek("(.*?)(\n|$)", $m, $count)) {
3494 throw new exception("$msg: failed at `$m[1]` $loc");
3495 } else {
3496 throw new exception("$msg: $loc");
3497 }
3498 }
3499
3500 protected function pushBlock($selectors=null, $type=null) {
3501 $b = new stdclass;
3502 $b->parent = $this->env;
3503
3504 $b->type = $type;
3505 $b->id = self::$nextBlockId++;
3506
3507 $b->isVararg = false; // TODO: kill me from here
3508 $b->tags = $selectors;
3509
3510 $b->props = array();
3511 $b->children = array();
3512
3513 $this->env = $b;
3514 return $b;
3515 }
3516
3517 // push a block that doesn't multiply tags
3518 protected function pushSpecialBlock($type) {
3519 return $this->pushBlock(null, $type);
3520 }
3521
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;
3526 }
3527
3528 // pop something off the stack
3529 protected function pop() {
3530 $old = $this->env;
3531 $this->env = $this->env->parent;
3532 return $old;
3533 }
3534
3535 // remove comments from $text
3536 // todo: make it work for all functions, not just url
3537 protected function removeComments($text) {
3538 $look = array(
3539 'url(', '//', '/*', '"', "'"
3540 );
3541
3542 $out = '';
3543 $min = null;
3544 while (true) {
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);
3550 }
3551 }
3552
3553 if (is_null($min)) break;
3554
3555 $count = $min[1];
3556 $skip = 0;
3557 $newlines = 0;
3558 switch ($min[0]) {
3559 case 'url(':
3560 if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
3561 $count += strlen($m[0]) - strlen($min[0]);
3562 break;
3563 case '"':
3564 case "'":
3565 if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count))
3566 $count += strlen($m[0]) - 1;
3567 break;
3568 case '//':
3569 $skip = strpos($text, "\n", $count);
3570 if ($skip === false) $skip = strlen($text) - $count;
3571 else $skip -= $count;
3572 break;
3573 case '/*':
3574 if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
3575 $skip = strlen($m[0]);
3576 $newlines = substr_count($m[0], "\n");
3577 }
3578 break;
3579 }
3580
3581 if ($skip == 0) $count += strlen($min[0]);
3582
3583 $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
3584 $text = substr($text, $count + $skip);
3585
3586 $min = null;
3587 }
3588
3589 return $out.$text;
3590 }
3591
3592 }
3593
3594 class lessc_formatter_classic {
3595 public $indentChar = " ";
3596
3597 public $break = "\n";
3598 public $open = " {";
3599 public $close = "}";
3600 public $selectorSeparator = ", ";
3601 public $assignSeparator = ":";
3602
3603 public $openSingle = " { ";
3604 public $closeSingle = " }";
3605
3606 public $disableSingle = false;
3607 public $breakSelectors = false;
3608
3609 public $compressColors = false;
3610
3611 public function __construct() {
3612 $this->indentLevel = 0;
3613 }
3614
3615 public function indentStr($n = 0) {
3616 return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
3617 }
3618
3619 public function property($name, $value) {
3620 return $name . $this->assignSeparator . $value . ";";
3621 }
3622
3623 protected function isEmpty($block) {
3624 if (empty($block->lines)) {
3625 foreach ($block->children as $child) {
3626 if (!$this->isEmpty($child)) return false;
3627 }
3628
3629 return true;
3630 }
3631 return false;
3632 }
3633
3634 public function block($block) {
3635 if ($this->isEmpty($block)) return;
3636
3637 $inner = $pre = $this->indentStr();
3638
3639 $isSingle = !$this->disableSingle &&
3640 is_null($block->type) && count($block->lines) == 1;
3641
3642 if (!empty($block->selectors)) {
3643 $this->indentLevel++;
3644
3645 if ($this->breakSelectors) {
3646 $selectorSeparator = $this->selectorSeparator . $this->break . $pre;
3647 } else {
3648 $selectorSeparator = $this->selectorSeparator;
3649 }
3650
3651 echo $pre .
3652 implode($selectorSeparator, $block->selectors);
3653 if ($isSingle) {
3654 echo $this->openSingle;
3655 $inner = "";
3656 } else {
3657 echo $this->open . $this->break;
3658 $inner = $this->indentStr();
3659 }
3660
3661 }
3662
3663 if (!empty($block->lines)) {
3664 $glue = $this->break.$inner;
3665 echo $inner . implode($glue, $block->lines);
3666 if (!$isSingle && !empty($block->children)) {
3667 echo $this->break;
3668 }
3669 }
3670
3671 foreach ($block->children as $child) {
3672 $this->block($child);
3673 }
3674
3675 if (!empty($block->selectors)) {
3676 if (!$isSingle && empty($block->children)) echo $this->break;
3677
3678 if ($isSingle) {
3679 echo $this->closeSingle . $this->break;
3680 } else {
3681 echo $pre . $this->close . $this->break;
3682 }
3683
3684 $this->indentLevel--;
3685 }
3686 }
3687 }
3688
3689 class lessc_formatter_compressed extends lessc_formatter_classic {
3690 public $disableSingle = true;
3691 public $open = "{";
3692 public $selectorSeparator = ",";
3693 public $assignSeparator = ":";
3694 public $break = "";
3695 public $compressColors = true;
3696
3697 public function indentStr($n = 0) {
3698 return "";
3699 }
3700 }
3701
3702 class lessc_formatter_lessjs extends lessc_formatter_classic {
3703 public $disableSingle = true;
3704 public $breakSelectors = true;
3705 public $assignSeparator = ": ";
3706 public $selectorSeparator = ",";
3707 }
3708
3709