dolibarr 21.0.0-alpha
lessc.class.php
1<?php
2
14// phpcs:disable
41class Lessc
42{
43
44 public static $VERSION = "v0.8.0";
45
46 public static $TRUE = array("keyword", "true");
47 public static $FALSE = array("keyword", "false");
48
49 protected $libFunctions = array();
50 protected $registeredVars = array();
51 protected $preserveComments = false;
52
53 public $vPrefix = '@'; // prefix of abstract properties
54 public $mPrefix = '$'; // prefix of abstract blocks
55 public $parentSelector = '&';
56
57 public $importDisabled = false;
58 public $importDir = '';
59
60 public $scope;
61 public $formatter;
62 public $formatterName;
63 public $parser;
64 public $_parseFile;
65 public $env;
66 public $count;
67
68 protected $numberPrecision = null;
69
70 protected $allParsedFiles = array();
71
72 // set to the parser that generated the current line when compiling
73 // so we know how to create error messages
74 protected $sourceParser = null;
75 protected $sourceLoc = null;
76
77 protected static $nextImportId = 0; // uniquely identify imports
78
79 // attempts to find the path of an import url, returns null for css files
80 protected function findImport($url)
81 {
82 foreach ((array) $this->importDir as $dir) {
83 $full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
84 if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
85 return $file;
86 }
87 }
88
89 return null;
90 }
91
98 protected function fileExists($name)
99 {
100 return is_file($name);
101 }
102
103 public static function compressList($items, $delim)
104 {
105 if (!isset($items[1]) && isset($items[0])) {
106 return $items[0];
107 } else {
108 return array('list', $delim, $items);
109 }
110 }
111
112 public static function preg_quote($what)
113 {
114 return preg_quote($what, '/');
115 }
116
117 protected function tryImport($importPath, $parentBlock, $out)
118 {
119 if ($importPath[0] == "function" && $importPath[1] == "url") {
120 $importPath = $this->flattenList($importPath[2]);
121 }
122
123 $str = $this->coerceString($importPath);
124 if ($str === null) {
125 return false;
126 }
127
128 $url = $this->compileValue($this->lib_e($str));
129
130 // don't import if it ends in css
131 if (substr_compare($url, '.css', -4, 4) === 0) {
132 return false;
133 }
134
135 $realPath = $this->findImport($url);
136
137 if ($realPath === null) {
138 return false;
139 }
140
141 if ($this->importDisabled) {
142 return array(false, "/* import disabled */");
143 }
144
145 if (isset($this->allParsedFiles[realpath($realPath)])) {
146 return array(false, null);
147 }
148
149 $this->addParsedFile($realPath);
150 $parser = $this->makeParser($realPath);
151 $root = $parser->parse(file_get_contents($realPath));
152
153 // set the parents of all the block props
154 foreach ($root->props as $prop) {
155 if ($prop[0] == "block") {
156 $prop[1]->parent = $parentBlock;
157 }
158 }
159
160 // copy mixins into scope, set their parents
161 // bring blocks from import into current block
162 // TODO: need to mark the source parser these came from this file
163 foreach ($root->children as $childName => $child) {
164 if (isset($parentBlock->children[$childName])) {
165 $parentBlock->children[$childName] = array_merge(
166 $parentBlock->children[$childName],
167 $child
168 );
169 } else {
170 $parentBlock->children[$childName] = $child;
171 }
172 }
173
174 $pi = pathinfo($realPath);
175 $dir = $pi["dirname"];
176
177 list($top, $bottom) = $this->sortProps($root->props, true);
178 $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
179
180 return array(true, $bottom, $parser, $dir);
181 }
182
183 protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir)
184 {
185 $oldSourceParser = $this->sourceParser;
186
187 $oldImport = $this->importDir;
188
189 // TODO: this is because the importDir api is stupid
190 $this->importDir = (array) $this->importDir;
191 array_unshift($this->importDir, $importDir);
192
193 foreach ($props as $prop) {
194 $this->compileProp($prop, $block, $out);
195 }
196
197 $this->importDir = $oldImport;
198 $this->sourceParser = $oldSourceParser;
199 }
200
222 protected function compileBlock($block)
223 {
224 switch ($block->type) {
225 case "root":
226 $this->compileRoot($block);
227 break;
228 case null:
229 $this->compileCSSBlock($block);
230 break;
231 case "media":
232 $this->compileMedia($block);
233 break;
234 case "directive":
235 $name = "@".$block->name;
236 if (!empty($block->value)) {
237 $name .= " ".$this->compileValue($this->reduce($block->value));
238 }
239
240 $this->compileNestedBlock($block, array($name));
241 break;
242 default:
243 $this->throwError("unknown block type: $block->type\n");
244 }
245 }
246
247 protected function compileCSSBlock($block)
248 {
249 $env = $this->pushEnv();
250
251 $selectors = $this->compileSelectors($block->tags);
252 $env->selectors = $this->multiplySelectors($selectors);
253 $out = $this->makeOutputBlock(null, $env->selectors);
254
255 $this->scope->children[] = $out;
256 $this->compileProps($block, $out);
257
258 $block->scope = $env; // mixins carry scope with them!
259 $this->popEnv();
260 }
261
262 protected function compileMedia($media)
263 {
264 $env = $this->pushEnv($media);
265 $parentScope = $this->mediaParent($this->scope);
266
267 $query = $this->compileMediaQuery($this->multiplyMedia($env));
268
269 $this->scope = $this->makeOutputBlock($media->type, array($query));
270 $parentScope->children[] = $this->scope;
271
272 $this->compileProps($media, $this->scope);
273
274 if (count($this->scope->lines) > 0) {
275 $orphanSelelectors = $this->findClosestSelectors();
276 if (!is_null($orphanSelelectors)) {
277 $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
278 $orphan->lines = $this->scope->lines;
279 array_unshift($this->scope->children, $orphan);
280 $this->scope->lines = array();
281 }
282 }
283
284 $this->scope = $this->scope->parent;
285 $this->popEnv();
286 }
287
288 protected function mediaParent($scope)
289 {
290 while (!empty($scope->parent)) {
291 if (!empty($scope->type) && $scope->type != "media") {
292 break;
293 }
294 $scope = $scope->parent;
295 }
296
297 return $scope;
298 }
299
300 protected function compileNestedBlock($block, $selectors)
301 {
302 $this->pushEnv($block);
303 $this->scope = $this->makeOutputBlock($block->type, $selectors);
304 $this->scope->parent->children[] = $this->scope;
305
306 $this->compileProps($block, $this->scope);
307
308 $this->scope = $this->scope->parent;
309 $this->popEnv();
310 }
311
312 protected function compileRoot($root)
313 {
314 $this->pushEnv();
315 $this->scope = $this->makeOutputBlock($root->type);
316 $this->compileProps($root, $this->scope);
317 $this->popEnv();
318 }
319
320 protected function compileProps($block, $out)
321 {
322 foreach ($this->sortProps($block->props) as $prop) {
323 $this->compileProp($prop, $block, $out);
324 }
325 $out->lines = $this->deduplicate($out->lines);
326 }
327
333 protected function deduplicate($lines)
334 {
335 $unique = array();
336 $comments = array();
337
338 foreach ($lines as $line) {
339 if (strpos($line, '/*') === 0) {
340 $comments[] = $line;
341 continue;
342 }
343 if (!in_array($line, $unique)) {
344 $unique[] = $line;
345 }
346 array_splice($unique, array_search($line, $unique), 0, $comments);
347 $comments = array();
348 }
349 return array_merge($unique, $comments);
350 }
351
352 protected function sortProps($props, $split = false)
353 {
354 $vars = array();
355 $imports = array();
356 $other = array();
357 $stack = array();
358
359 foreach ($props as $prop) {
360 switch ($prop[0]) {
361 case "comment":
362 $stack[] = $prop;
363 break;
364 case "assign":
365 $stack[] = $prop;
366 if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) {
367 $vars = array_merge($vars, $stack);
368 } else {
369 $other = array_merge($other, $stack);
370 }
371 $stack = array();
372 break;
373 case "import":
374 $id = self::$nextImportId++;
375 $prop[] = $id;
376 $stack[] = $prop;
377 $imports = array_merge($imports, $stack);
378 $other[] = array("import_mixin", $id);
379 $stack = array();
380 break;
381 default:
382 $stack[] = $prop;
383 $other = array_merge($other, $stack);
384 $stack = array();
385 break;
386 }
387 }
388 $other = array_merge($other, $stack);
389
390 if ($split) {
391 return array(array_merge($imports, $vars), $other);
392 } else {
393 return array_merge($imports, $vars, $other);
394 }
395 }
396
397 protected function compileMediaQuery($queries)
398 {
399 $compiledQueries = array();
400 foreach ($queries as $query) {
401 $parts = array();
402 foreach ($query as $q) {
403 switch ($q[0]) {
404 case "mediaType":
405 $parts[] = implode(" ", array_slice($q, 1));
406 break;
407 case "mediaExp":
408 if (isset($q[2])) {
409 $parts[] = "($q[1]: ".
410 $this->compileValue($this->reduce($q[2])).")";
411 } else {
412 $parts[] = "($q[1])";
413 }
414 break;
415 case "variable":
416 $parts[] = $this->compileValue($this->reduce($q));
417 break;
418 }
419 }
420
421 if (count($parts) > 0) {
422 $compiledQueries[] = implode(" and ", $parts);
423 }
424 }
425
426 $out = "@media";
427 if (!empty($parts)) {
428 $out .= " ".
429 implode($this->formatter->selectorSeparator, $compiledQueries);
430 }
431 return $out;
432 }
433
434 protected function multiplyMedia($env, $childQueries = null)
435 {
436 if (is_null($env) ||
437 !empty($env->block->type) && $env->block->type != "media"
438 ) {
439 return $childQueries;
440 }
441
442 // plain old block, skip
443 if (empty($env->block->type)) {
444 return $this->multiplyMedia($env->parent, $childQueries);
445 }
446
447 $out = array();
448 $queries = $env->block->queries;
449 if (is_null($childQueries)) {
450 $out = $queries;
451 } else {
452 foreach ($queries as $parent) {
453 foreach ($childQueries as $child) {
454 $out[] = array_merge($parent, $child);
455 }
456 }
457 }
458
459 return $this->multiplyMedia($env->parent, $out);
460 }
461
462 protected function expandParentSelectors(&$tag, $replace)
463 {
464 $parts = explode("$&$", $tag);
465 $count = 0;
466 foreach ($parts as &$part) {
467 $c = 0;
468 $part = str_replace($this->parentSelector, $replace, $part, $c);
469 $count += $c;
470 }
471 $tag = implode($this->parentSelector, $parts);
472 return $count;
473 }
474
475 protected function findClosestSelectors()
476 {
477 $env = $this->env;
478 $selectors = null;
479 while ($env !== null) {
480 if (isset($env->selectors)) {
481 $selectors = $env->selectors;
482 break;
483 }
484 $env = $env->parent;
485 }
486
487 return $selectors;
488 }
489
490
491 // multiply $selectors against the nearest selectors in env
492 protected function multiplySelectors($selectors)
493 {
494 // find parent selectors
495
496 $parentSelectors = $this->findClosestSelectors();
497 if (is_null($parentSelectors)) {
498 // kill parent reference in top level selector
499 foreach ($selectors as &$s) {
500 $this->expandParentSelectors($s, "");
501 }
502
503 return $selectors;
504 }
505
506 $out = array();
507 foreach ($parentSelectors as $parent) {
508 foreach ($selectors as $child) {
509 $count = $this->expandParentSelectors($child, $parent);
510
511 // don't prepend the parent tag if & was used
512 if ($count > 0) {
513 $out[] = trim($child);
514 } else {
515 $out[] = trim($parent.' '.$child);
516 }
517 }
518 }
519
520 return $out;
521 }
522
523 // reduces selector expressions
524 protected function compileSelectors($selectors)
525 {
526 $out = array();
527
528 foreach ($selectors as $s) {
529 if (is_array($s)) {
530 list(, $value) = $s;
531 $out[] = trim($this->compileValue($this->reduce($value)));
532 } else {
533 $out[] = $s;
534 }
535 }
536
537 return $out;
538 }
539
540 protected function eq($left, $right)
541 {
542 return $left == $right;
543 }
544
545 protected function patternMatch($block, $orderedArgs, $keywordArgs)
546 {
547 // match the guards if it has them
548 // any one of the groups must have all its guards pass for a match
549 if (!empty($block->guards)) {
550 $groupPassed = false;
551 foreach ($block->guards as $guardGroup) {
552 foreach ($guardGroup as $guard) {
553 $this->pushEnv();
554 $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
555
556 $negate = false;
557 if ($guard[0] == "negate") {
558 $guard = $guard[1];
559 $negate = true;
560 }
561
562 $passed = $this->reduce($guard) == self::$TRUE;
563 if ($negate) {
564 $passed = !$passed;
565 }
566
567 $this->popEnv();
568
569 if ($passed) {
570 $groupPassed = true;
571 } else {
572 $groupPassed = false;
573 break;
574 }
575 }
576
577 if ($groupPassed) {
578 break;
579 }
580 }
581
582 if (!$groupPassed) {
583 return false;
584 }
585 }
586
587 if (empty($block->args)) {
588 return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
589 }
590
591 $remainingArgs = $block->args;
592 if ($keywordArgs) {
593 $remainingArgs = array();
594 foreach ($block->args as $arg) {
595 if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
596 continue;
597 }
598
599 $remainingArgs[] = $arg;
600 }
601 }
602
603 $i = -1; // no args
604 // try to match by arity or by argument literal
605 foreach ($remainingArgs as $i => $arg) {
606 switch ($arg[0]) {
607 case "lit":
608 if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
609 return false;
610 }
611 break;
612 case "arg":
613 // no arg and no default value
614 if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
615 return false;
616 }
617 break;
618 case "rest":
619 $i--; // rest can be empty
620 break 2;
621 }
622 }
623
624 if ($block->isVararg) {
625 return true; // not having enough is handled above
626 } else {
627 $numMatched = $i + 1;
628 // greater than because default values always match
629 return $numMatched >= count($orderedArgs);
630 }
631 }
632
633 protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip = array())
634 {
635 $matches = null;
636 foreach ($blocks as $block) {
637 // skip seen blocks that don't have arguments
638 if (isset($skip[$block->id]) && !isset($block->args)) {
639 continue;
640 }
641
642 if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
643 $matches[] = $block;
644 }
645 }
646
647 return $matches;
648 }
649
650 // attempt to find blocks matched by path and args
651 protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen = array())
652 {
653 if ($searchIn == null) {
654 return null;
655 }
656 if (isset($seen[$searchIn->id])) {
657 return null;
658 }
659 $seen[$searchIn->id] = true;
660
661 $name = $path[0];
662
663 if (isset($searchIn->children[$name])) {
664 $blocks = $searchIn->children[$name];
665 if (count($path) == 1) {
666 $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
667 if (!empty($matches)) {
668 // This will return all blocks that match in the closest
669 // scope that has any matching block, like lessjs
670 return $matches;
671 }
672 } else {
673 $matches = array();
674 foreach ($blocks as $subBlock) {
675 $subMatches = $this->findBlocks(
676 $subBlock,
677 array_slice($path, 1),
678 $orderedArgs,
679 $keywordArgs,
680 $seen
681 );
682
683 if (!is_null($subMatches)) {
684 foreach ($subMatches as $sm) {
685 $matches[] = $sm;
686 }
687 }
688 }
689
690 return count($matches) > 0 ? $matches : null;
691 }
692 }
693 if ($searchIn->parent === $searchIn) {
694 return null;
695 }
696 return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
697 }
698
699 // sets all argument names in $args to either the default value
700 // or the one passed in through $values
701 protected function zipSetArgs($args, $orderedValues, $keywordValues)
702 {
703 $assignedValues = array();
704
705 $i = 0;
706 foreach ($args as $a) {
707 if ($a[0] == "arg") {
708 if (isset($keywordValues[$a[1]])) {
709 // has keyword arg
710 $value = $keywordValues[$a[1]];
711 } elseif (isset($orderedValues[$i])) {
712 // has ordered arg
713 $value = $orderedValues[$i];
714 $i++;
715 } elseif (isset($a[2])) {
716 // has default value
717 $value = $a[2];
718 } else {
719 $value = null; // :(
720 $this->throwError("Failed to assign arg ".$a[1]); // This ends function by throwing an exception
721 }
722
723 $value = $this->reduce($value);
724 $this->set($a[1], $value);
725 $assignedValues[] = $value;
726 } else {
727 // a lit
728 $i++;
729 }
730 }
731
732 // check for a rest
733 $last = end($args);
734 if ($last && $last[0] == "rest") {
735 $rest = array_slice($orderedValues, count($args) - 1);
736 $this->set($last[1], $this->reduce(array("list", " ", $rest)));
737 }
738
739 // wow is this the only true use of PHP's + operator for arrays?
740 $this->env->arguments = $assignedValues + $orderedValues;
741 }
742
743 // compile a prop and update $lines or $blocks appropriately
744 protected function compileProp($prop, $block, $out)
745 {
746 // set error position context
747 $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;
748
749 switch ($prop[0]) {
750 case 'assign':
751 list(, $name, $value) = $prop;
752 if ($name[0] == $this->vPrefix) {
753 $this->set($name, $value);
754 } else {
755 $out->lines[] = $this->formatter->property(
756 $name,
757 $this->compileValue($this->reduce($value))
758 );
759 }
760 break;
761 case 'block':
762 list(, $child) = $prop;
763 $this->compileBlock($child);
764 break;
765 case 'mixin':
766 list(, $path, $args, $suffix) = $prop;
767
768 $orderedArgs = array();
769 $keywordArgs = array();
770 foreach ((array) $args as $arg) {
771 $argval = null;
772 switch ($arg[0]) {
773 case "arg":
774 if (!isset($arg[2])) {
775 $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
776 } else {
777 $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
778 }
779 break;
780
781 case "lit":
782 $orderedArgs[] = $this->reduce($arg[1]);
783 break;
784 default:
785 $this->throwError("Unknown arg type: ".$arg[0]);
786 }
787 }
788
789 $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
790
791 if ($mixins === null) {
792 $this->throwError("{$prop[1][0]} is undefined");
793 }
794
795 foreach ($mixins as $mixin) {
796 if ($mixin === $block && !$orderedArgs) {
797 continue;
798 }
799
800 $haveScope = false;
801 if (isset($mixin->parent->scope)) {
802 $haveScope = true;
803 $mixinParentEnv = $this->pushEnv();
804 $mixinParentEnv->storeParent = $mixin->parent->scope;
805 }
806
807 $haveArgs = false;
808 if (isset($mixin->args)) {
809 $haveArgs = true;
810 $this->pushEnv();
811 $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs);
812 }
813
814 $oldParent = $mixin->parent;
815 if ($mixin != $block) {
816 $mixin->parent = $block;
817 }
818
819 foreach ($this->sortProps($mixin->props) as $subProp) {
820 if ($suffix !== null &&
821 $subProp[0] == "assign" &&
822 is_string($subProp[1]) &&
823 $subProp[1][0] != $this->vPrefix
824 ) {
825 $subProp[2] = array(
826 'list', ' ',
827 array($subProp[2], array('keyword', $suffix))
828 );
829 }
830
831 $this->compileProp($subProp, $mixin, $out);
832 }
833
834 $mixin->parent = $oldParent;
835
836 if ($haveArgs) {
837 $this->popEnv();
838 }
839 if ($haveScope) {
840 $this->popEnv();
841 }
842 }
843
844 break;
845 case 'raw':
846 $out->lines[] = $prop[1];
847 break;
848 case "directive":
849 list(, $name, $value) = $prop;
850 $out->lines[] = "@$name ".$this->compileValue($this->reduce($value)).';';
851 break;
852 case "comment":
853 $out->lines[] = $prop[1];
854 break;
855 case "import":
856 list(, $importPath, $importId) = $prop;
857 $importPath = $this->reduce($importPath);
858
859 if (!isset($this->env->imports)) {
860 $this->env->imports = array();
861 }
862
863 $result = $this->tryImport($importPath, $block, $out);
864
865 $this->env->imports[$importId] = $result === false ?
866 array(false, "@import ".$this->compileValue($importPath).";") : $result;
867
868 break;
869 case "import_mixin":
870 list(, $importId) = $prop;
871 $import = $this->env->imports[$importId];
872 if ($import[0] === false) {
873 if (isset($import[1])) {
874 $out->lines[] = $import[1];
875 }
876 } else {
877 list(, $bottom, $parser, $importDir) = $import;
878 $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
879 }
880
881 break;
882 default:
883 $this->throwError("unknown op: {$prop[0]}\n");
884 }
885 }
886
887
899 public function compileValue($value)
900 {
901 switch ($value[0]) {
902 case 'list':
903 // [1] - delimiter
904 // [2] - array of values
905 return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
906 case 'raw_color':
907 if (!empty($this->formatter->compressColors)) {
908 return $this->compileValue($this->coerceColor($value));
909 }
910 return $value[1];
911 case 'keyword':
912 // [1] - the keyword
913 return $value[1];
914 case 'number':
915 list(, $num, $unit) = $value;
916 // [1] - the number
917 // [2] - the unit
918 if ($this->numberPrecision !== null) {
919 $num = round($num, $this->numberPrecision);
920 }
921 return $num.$unit;
922 case 'string':
923 // [1] - contents of string (includes quotes)
924 list(, $delim, $content) = $value;
925 foreach ($content as &$part) {
926 if (is_array($part)) {
927 $part = $this->compileValue($part);
928 }
929 }
930 return $delim.implode($content).$delim;
931 case 'color':
932 // [1] - red component (either number or a %)
933 // [2] - green component
934 // [3] - blue component
935 // [4] - optional alpha component
936 list(, $r, $g, $b) = $value;
937 $r = round($r);
938 $g = round($g);
939 $b = round($b);
940
941 if (count($value) == 5 && $value[4] != 1) { // rgba
942 return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
943 }
944
945 $h = sprintf("#%02x%02x%02x", $r, $g, $b);
946
947 if (!empty($this->formatter->compressColors)) {
948 // Converting hex color to short notation (e.g. #003399 to #039)
949 if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
950 $h = '#'.$h[1].$h[3].$h[5];
951 }
952 }
953
954 return $h;
955
956 case 'function':
957 list(, $name, $args) = $value;
958 return $name.'('.$this->compileValue($args).')';
959 default: // assumed to be unit
960 $this->throwError("unknown value type: $value[0]");
961 }
962 }
963
964 protected function lib_pow($args)
965 {
966 list($base, $exp) = $this->assertArgs($args, 2, "pow");
967 return pow($this->assertNumber($base), $this->assertNumber($exp));
968 }
969
970 protected function lib_pi()
971 {
972 return pi();
973 }
974
975 protected function lib_mod($args)
976 {
977 list($a, $b) = $this->assertArgs($args, 2, "mod");
978 return $this->assertNumber($a) % $this->assertNumber($b);
979 }
980
981 protected function lib_tan($num)
982 {
983 return tan($this->assertNumber($num));
984 }
985
986 protected function lib_sin($num)
987 {
988 return sin($this->assertNumber($num));
989 }
990
991 protected function lib_cos($num)
992 {
993 return cos($this->assertNumber($num));
994 }
995
996 protected function lib_atan($num)
997 {
998 $num = atan($this->assertNumber($num));
999 return array("number", $num, "rad");
1000 }
1001
1002 protected function lib_asin($num)
1003 {
1004 $num = asin($this->assertNumber($num));
1005 return array("number", $num, "rad");
1006 }
1007
1008 protected function lib_acos($num)
1009 {
1010 $num = acos($this->assertNumber($num));
1011 return array("number", $num, "rad");
1012 }
1013
1014 protected function lib_sqrt($num)
1015 {
1016 return sqrt($this->assertNumber($num));
1017 }
1018
1019 protected function lib_extract($value)
1020 {
1021 list($list, $idx) = $this->assertArgs($value, 2, "extract");
1022 $idx = $this->assertNumber($idx);
1023 // 1 indexed
1024 if ($list[0] == "list" && isset($list[2][$idx - 1])) {
1025 return $list[2][$idx - 1];
1026 }
1027 return '';
1028 }
1029
1030 protected function lib_isnumber($value)
1031 {
1032 return $this->toBool($value[0] == "number");
1033 }
1034
1035 protected function lib_isstring($value)
1036 {
1037 return $this->toBool($value[0] == "string");
1038 }
1039
1040 protected function lib_iscolor($value)
1041 {
1042 return $this->toBool($this->coerceColor($value));
1043 }
1044
1045 protected function lib_iskeyword($value)
1046 {
1047 return $this->toBool($value[0] == "keyword");
1048 }
1049
1050 protected function lib_ispixel($value)
1051 {
1052 return $this->toBool($value[0] == "number" && $value[2] == "px");
1053 }
1054
1055 protected function lib_ispercentage($value)
1056 {
1057 return $this->toBool($value[0] == "number" && $value[2] == "%");
1058 }
1059
1060 protected function lib_isem($value)
1061 {
1062 return $this->toBool($value[0] == "number" && $value[2] == "em");
1063 }
1064
1065 protected function lib_isrem($value)
1066 {
1067 return $this->toBool($value[0] == "number" && $value[2] == "rem");
1068 }
1069
1070 protected function lib_rgbahex($color)
1071 {
1072 $color = $this->coerceColor($color);
1073 if (is_null($color)) {
1074 $this->throwError("color expected for rgbahex");
1075 }
1076
1077 return sprintf(
1078 "#%02x%02x%02x%02x",
1079 isset($color[4]) ? $color[4] * 255 : 255,
1080 $color[1],
1081 $color[2],
1082 $color[3]
1083 );
1084 }
1085
1086 protected function lib_argb($color)
1087 {
1088 return $this->lib_rgbahex($color);
1089 }
1090
1097 protected function lib_data_uri($value)
1098 {
1099 $mime = ($value[0] === 'list') ? $value[2][0][2] : null;
1100 $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0];
1101
1102 $fullpath = $this->findImport($url);
1103
1104 if ($fullpath && ($fsize = filesize($fullpath)) !== false) {
1105 // IE8 can't handle data uris larger than 32KB
1106 if ($fsize / 1024 < 32) {
1107 if (is_null($mime)) {
1108 if (class_exists('finfo')) { // php 5.3+
1109 $finfo = new finfo(FILEINFO_MIME);
1110 $mime = explode('; ', $finfo->file($fullpath));
1111 $mime = $mime[0];
1112 } elseif (function_exists('mime_content_type')) { // PHP 5.2
1113 $mime = mime_content_type($fullpath);
1114 }
1115 }
1116
1117 if (!is_null($mime)) { // fallback if the mime type is still unknown
1118 $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
1119 }
1120 }
1121 }
1122
1123 return 'url("'.$url.'")';
1124 }
1125
1126 // utility func to unquote a string
1127 protected function lib_e($arg)
1128 {
1129 switch ($arg[0]) {
1130 case "list":
1131 $items = $arg[2];
1132 if (isset($items[0])) {
1133 return $this->lib_e($items[0]);
1134 }
1135 $this->throwError("unrecognised input"); // This ends function by throwing an exception
1136 // no break
1137 case "string":
1138 $arg[1] = "";
1139 return $arg;
1140 case "keyword":
1141 return $arg;
1142 default:
1143 return array("keyword", $this->compileValue($arg));
1144 }
1145 }
1146
1147 protected function lib__sprintf($args)
1148 {
1149 if ($args[0] != "list") {
1150 return $args;
1151 }
1152 $values = $args[2];
1153 $string = array_shift($values);
1154 $template = $this->compileValue($this->lib_e($string));
1155
1156 $i = 0;
1157 $m = array();
1158 if (preg_match_all('/%[dsa]/', $template, $m)) {
1159 foreach ($m[0] as $match) {
1160 $val = isset($values[$i]) ?
1161 $this->reduce($values[$i]) : array('keyword', '');
1162
1163 // lessjs compat, renders fully expanded color, not raw color
1164 if ($color = $this->coerceColor($val)) {
1165 $val = $color;
1166 }
1167
1168 $i++;
1169 $rep = $this->compileValue($this->lib_e($val));
1170 $template = preg_replace(
1171 '/'.self::preg_quote($match).'/',
1172 $rep,
1173 $template,
1174 1
1175 );
1176 }
1177 }
1178
1179 $d = $string[0] == "string" ? $string[1] : '"';
1180 return array("string", $d, array($template));
1181 }
1182
1183 protected function lib_floor($arg)
1184 {
1185 $value = $this->assertNumber($arg);
1186 return array("number", floor($value), $arg[2]);
1187 }
1188
1189 protected function lib_ceil($arg)
1190 {
1191 $value = $this->assertNumber($arg);
1192 return array("number", ceil($value), $arg[2]);
1193 }
1194
1195 protected function lib_round($arg)
1196 {
1197 if ($arg[0] != "list") {
1198 $value = $this->assertNumber($arg);
1199 return array("number", round($value), $arg[2]);
1200 } else {
1201 $value = $this->assertNumber($arg[2][0]);
1202 $precision = $this->assertNumber($arg[2][1]);
1203 return array("number", round($value, $precision), $arg[2][0][2]);
1204 }
1205 }
1206
1207 protected function lib_unit($arg)
1208 {
1209 if ($arg[0] == "list") {
1210 list($number, $newUnit) = $arg[2];
1211 return array("number", $this->assertNumber($number),
1212 $this->compileValue($this->lib_e($newUnit)));
1213 } else {
1214 return array("number", $this->assertNumber($arg), "");
1215 }
1216 }
1217
1222 public function colorArgs($args)
1223 {
1224 if ($args[0] != 'list' || count($args[2]) < 2) {
1225 return array(array('color', 0, 0, 0), 0);
1226 }
1227 list($color, $delta) = $args[2];
1228 $color = $this->assertColor($color);
1229 $delta = (float) $delta[1];
1230
1231 return array($color, $delta);
1232 }
1233
1234 protected function lib_darken($args)
1235 {
1236 list($color, $delta) = $this->colorArgs($args);
1237
1238 $hsl = $this->toHSL($color);
1239 $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
1240 return $this->toRGB($hsl);
1241 }
1242
1243 protected function lib_lighten($args)
1244 {
1245 list($color, $delta) = $this->colorArgs($args);
1246
1247 $hsl = $this->toHSL($color);
1248 $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
1249 return $this->toRGB($hsl);
1250 }
1251
1252 protected function lib_saturate($args)
1253 {
1254 list($color, $delta) = $this->colorArgs($args);
1255
1256 $hsl = $this->toHSL($color);
1257 $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
1258 return $this->toRGB($hsl);
1259 }
1260
1261 protected function lib_desaturate($args)
1262 {
1263 list($color, $delta) = $this->colorArgs($args);
1264
1265 $hsl = $this->toHSL($color);
1266 $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
1267 return $this->toRGB($hsl);
1268 }
1269
1270 protected function lib_spin($args)
1271 {
1272 list($color, $delta) = $this->colorArgs($args);
1273
1274 $hsl = $this->toHSL($color);
1275
1276 $hsl[1] = $hsl[1] + $delta % 360;
1277 if ($hsl[1] < 0) {
1278 $hsl[1] += 360;
1279 }
1280
1281 return $this->toRGB($hsl);
1282 }
1283
1284 protected function lib_fadeout($args)
1285 {
1286 list($color, $delta) = $this->colorArgs($args);
1287 $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta / 100);
1288 return $color;
1289 }
1290
1291 protected function lib_fadein($args)
1292 {
1293 list($color, $delta) = $this->colorArgs($args);
1294 $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta / 100);
1295 return $color;
1296 }
1297
1298 protected function lib_hue($color)
1299 {
1300 $hsl = $this->toHSL($this->assertColor($color));
1301 return round($hsl[1]);
1302 }
1303
1304 protected function lib_saturation($color)
1305 {
1306 $hsl = $this->toHSL($this->assertColor($color));
1307 return round($hsl[2]);
1308 }
1309
1310 protected function lib_lightness($color)
1311 {
1312 $hsl = $this->toHSL($this->assertColor($color));
1313 return round($hsl[3]);
1314 }
1315
1316 // get the alpha of a color
1317 // defaults to 1 for non-colors or colors without an alpha
1318 protected function lib_alpha($value)
1319 {
1320 if (!is_null($color = $this->coerceColor($value))) {
1321 return isset($color[4]) ? $color[4] : 1;
1322 }
1323 return '';
1324 }
1325
1326 // set the alpha of the color
1327 protected function lib_fade($args)
1328 {
1329 list($color, $alpha) = $this->colorArgs($args);
1330 $color[4] = $this->clamp($alpha / 100.0);
1331 return $color;
1332 }
1333
1334 protected function lib_percentage($arg)
1335 {
1336 $num = $this->assertNumber($arg);
1337 return array("number", $num * 100, "%");
1338 }
1339
1351 protected function lib_tint($args)
1352 {
1353 $white = ['color', 255, 255, 255];
1354 if ($args[0] == 'color') {
1355 return $this->lib_mix(['list', ',', [$white, $args]]);
1356 } elseif ($args[0] == "list" && count($args[2]) == 2) {
1357 return $this->lib_mix([$args[0], $args[1], [$white, $args[2][0], $args[2][1]]]);
1358 } else {
1359 $this->throwError("tint expects (color, weight)");
1360 }
1361 return array();
1362 }
1363
1375 protected function lib_shade($args)
1376 {
1377 $black = ['color', 0, 0, 0];
1378 if ($args[0] == 'color') {
1379 return $this->lib_mix(['list', ',', [$black, $args]]);
1380 } elseif ($args[0] == "list" && count($args[2]) == 2) {
1381 return $this->lib_mix([$args[0], $args[1], [$black, $args[2][0], $args[2][1]]]);
1382 } else {
1383 $this->throwError("shade expects (color, weight)");
1384 }
1385 return array();
1386 }
1387
1397 protected function lib_mix($args)
1398 {
1399 if ($args[0] != "list" || count($args[2]) < 2) {
1400 $this->throwError("mix expects (color1, color2, weight)");
1401 }
1402
1403 list($first, $second) = $args[2];
1404 $first = $this->assertColor($first);
1405 $second = $this->assertColor($second);
1406
1407 $first_a = $this->lib_alpha($first);
1408 $second_a = $this->lib_alpha($second);
1409
1410 if (isset($args[2][2])) {
1411 $weight = $args[2][2][1] / 100.0;
1412 } else {
1413 $weight = 0.5;
1414 }
1415
1416 $w = $weight * 2 - 1;
1417 $a = $first_a - $second_a;
1418
1419 $w1 = (($w * $a == -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
1420 $w2 = 1.0 - $w1;
1421
1422 $new = array('color',
1423 $w1 * $first[1] + $w2 * $second[1],
1424 $w1 * $first[2] + $w2 * $second[2],
1425 $w1 * $first[3] + $w2 * $second[3],
1426 );
1427
1428 if ($first_a != 1.0 || $second_a != 1.0) {
1429 $new[] = $first_a * $weight + $second_a * ($weight - 1);
1430 }
1431
1432 return $this->fixColor($new);
1433 }
1434
1441 protected function lib_contrast($args)
1442 {
1443 $darkColor = array('color', 0, 0, 0);
1444 $lightColor = array('color', 255, 255, 255);
1445 $threshold = 0.43;
1446
1447 if ($args[0] == 'list') {
1448 $inputColor = (isset($args[2][0])) ? $this->assertColor($args[2][0]) : $lightColor;
1449 $darkColor = (isset($args[2][1])) ? $this->assertColor($args[2][1]) : $darkColor;
1450 $lightColor = (isset($args[2][2])) ? $this->assertColor($args[2][2]) : $lightColor;
1451 $threshold = (isset($args[2][3])) ? $this->assertNumber($args[2][3]) : $threshold;
1452 } else {
1453 $inputColor = $this->assertColor($args);
1454 }
1455
1456 $inputColor = $this->coerceColor($inputColor);
1457 $darkColor = $this->coerceColor($darkColor);
1458 $lightColor = $this->coerceColor($lightColor);
1459
1460 //Figure out which is actually light and dark!
1461 if ($this->toLuma($darkColor) > $this->toLuma($lightColor)) {
1462 $t = $lightColor;
1463 $lightColor = $darkColor;
1464 $darkColor = $t;
1465 }
1466
1467 $inputColor_alpha = $this->lib_alpha($inputColor);
1468 if (($this->toLuma($inputColor) * $inputColor_alpha) < $threshold) {
1469 return $lightColor;
1470 }
1471 return $darkColor;
1472 }
1473
1474 private function toLuma($color)
1475 {
1476 list(, $r, $g, $b) = $this->coerceColor($color);
1477
1478 $r = $r / 255;
1479 $g = $g / 255;
1480 $b = $b / 255;
1481
1482 $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
1483 $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
1484 $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
1485
1486 return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
1487 }
1488
1489 protected function lib_luma($color)
1490 {
1491 return array("number", round($this->toLuma($color) * 100, 8), "%");
1492 }
1493
1494
1495 public function assertColor($value, $error = "expected color value")
1496 {
1497 $color = $this->coerceColor($value);
1498 if (is_null($color)) {
1499 $this->throwError($error);
1500 }
1501 return $color;
1502 }
1503
1504 public function assertNumber($value, $error = "expecting number")
1505 {
1506 if ($value[0] == "number") {
1507 return $value[1];
1508 }
1509 $this->throwError($error);
1510 }
1511
1512 public function assertArgs($value, $expectedArgs, $name = "")
1513 {
1514 if ($expectedArgs == 1) {
1515 return $value;
1516 } else {
1517 if ($value[0] !== "list" || $value[1] != ",") {
1518 $this->throwError("expecting list");
1519 }
1520 $values = $value[2];
1521 $numValues = count($values);
1522 if ($expectedArgs != $numValues) {
1523 if ($name) {
1524 $name = $name.": ";
1525 }
1526
1527 $this->throwError("{$name}expecting $expectedArgs arguments, got $numValues");
1528 }
1529
1530 return $values;
1531 }
1532 }
1533
1534 protected function toHSL($color)
1535 {
1536 if ($color[0] === 'hsl') {
1537 return $color;
1538 }
1539
1540 $r = $color[1] / 255;
1541 $g = $color[2] / 255;
1542 $b = $color[3] / 255;
1543
1544 $min = min($r, $g, $b);
1545 $max = max($r, $g, $b);
1546
1547 $L = ($min + $max) / 2;
1548 if ($min == $max) {
1549 $S = $H = 0;
1550 } else {
1551 if ($L < 0.5) {
1552 $S = ($max - $min) / ($max + $min);
1553 } else {
1554 $S = ($max - $min) / (2.0 - $max - $min);
1555 }
1556 if ($r == $max) {
1557 $H = ($g - $b) / ($max - $min);
1558 } elseif ($g == $max) {
1559 $H = 2.0 + ($b - $r) / ($max - $min);
1560 } elseif ($b == $max) {
1561 $H = 4.0 + ($r - $g) / ($max - $min);
1562 }
1563 }
1564
1565 $out = array('hsl',
1566 ($H < 0 ? $H + 6 : $H) * 60,
1567 $S * 100,
1568 $L * 100,
1569 );
1570
1571 if (count($color) > 4) {
1572 // copy alpha
1573 $out[] = $color[4];
1574 }
1575 return $out;
1576 }
1577
1578 protected function toRGB_helper($comp, $temp1, $temp2)
1579 {
1580 if ($comp < 0) {
1581 $comp += 1.0;
1582 } elseif ($comp > 1) {
1583 $comp -= 1.0;
1584 }
1585
1586 if (6 * $comp < 1) {
1587 return $temp1 + ($temp2 - $temp1) * 6 * $comp;
1588 }
1589 if (2 * $comp < 1) {
1590 return $temp2;
1591 }
1592 if (3 * $comp < 2) {
1593 return $temp1 + ($temp2 - $temp1) * ((2 / 3) - $comp) * 6;
1594 }
1595
1596 return $temp1;
1597 }
1598
1603 protected function toRGB($color)
1604 {
1605 if ($color[0] === 'color') {
1606 return $color;
1607 }
1608
1609 $H = $color[1] / 360;
1610 $S = $color[2] / 100;
1611 $L = $color[3] / 100;
1612
1613 if ($S == 0) {
1614 $r = $g = $b = $L;
1615 } else {
1616 $temp2 = $L < 0.5 ?
1617 $L * (1.0 + $S) : $L + $S - $L * $S;
1618
1619 $temp1 = 2.0 * $L - $temp2;
1620
1621 $r = $this->toRGB_helper($H + 1 / 3, $temp1, $temp2);
1622 $g = $this->toRGB_helper($H, $temp1, $temp2);
1623 $b = $this->toRGB_helper($H - 1 / 3, $temp1, $temp2);
1624 }
1625
1626 // $out = array('color', round($r*255), round($g*255), round($b*255));
1627 $out = array('color', $r * 255, $g * 255, $b * 255);
1628 if (count($color) > 4) {
1629 // copy alpha
1630 $out[] = $color[4];
1631 }
1632 return $out;
1633 }
1634
1635 protected function clamp($v, $max = 1, $min = 0)
1636 {
1637 return min($max, max($min, $v));
1638 }
1639
1644 protected function funcToColor($func)
1645 {
1646 $fname = $func[1];
1647 if ($func[2][0] != 'list') {
1648 // need a list of arguments
1649 return false;
1650 }
1651 $rawComponents = $func[2][2];
1652
1653 if ($fname == 'hsl' || $fname == 'hsla') {
1654 $hsl = array('hsl');
1655 $i = 0;
1656 foreach ($rawComponents as $c) {
1657 $val = $this->reduce($c);
1658 $val = isset($val[1]) ? (float) $val[1] : 0;
1659
1660 if ($i == 0) {
1661 $clamp = 360;
1662 } elseif ($i < 3) {
1663 $clamp = 100;
1664 } else {
1665 $clamp = 1;
1666 }
1667
1668 $hsl[] = $this->clamp($val, $clamp);
1669 $i++;
1670 }
1671
1672 while (count($hsl) < 4) {
1673 $hsl[] = 0;
1674 }
1675 return $this->toRGB($hsl);
1676
1677 } elseif ($fname == 'rgb' || $fname == 'rgba') {
1678 $components = array();
1679 $i = 1;
1680 foreach ($rawComponents as $c) {
1681 $c = $this->reduce($c);
1682 if ($i < 4) {
1683 if ($c[0] == "number" && $c[2] == "%") {
1684 $components[] = 255 * ($c[1] / 100);
1685 } else {
1686 $components[] = (float) $c[1];
1687 }
1688 } elseif ($i == 4) {
1689 if ($c[0] == "number" && $c[2] == "%") {
1690 $components[] = 1.0 * ($c[1] / 100);
1691 } else {
1692 $components[] = (float) $c[1];
1693 }
1694 } else {
1695 break;
1696 }
1697
1698 $i++;
1699 }
1700 while (count($components) < 3) {
1701 $components[] = 0;
1702 }
1703 array_unshift($components, 'color');
1704 return $this->fixColor($components);
1705 }
1706
1707 return false;
1708 }
1709
1710 protected function reduce($value, $forExpression = false)
1711 {
1712 switch ($value[0]) {
1713 case "interpolate":
1714 $reduced = $this->reduce($value[1]);
1715 $var = $this->compileValue($reduced);
1716 $res = $this->reduce(array("variable", $this->vPrefix.$var));
1717
1718 if ($res[0] == "raw_color") {
1719 $res = $this->coerceColor($res);
1720 }
1721
1722 if (empty($value[2])) {
1723 $res = $this->lib_e($res);
1724 }
1725
1726 return $res;
1727 case "variable":
1728 $key = $value[1];
1729 if (is_array($key)) {
1730 $key = $this->reduce($key);
1731 $key = $this->vPrefix.$this->compileValue($this->lib_e($key));
1732 }
1733
1734 $seen = & $this->env->seenNames;
1735
1736 if (!empty($seen[$key])) {
1737 $this->throwError("infinite loop detected: $key");
1738 }
1739
1740 $seen[$key] = true;
1741 $out = $this->reduce($this->get($key));
1742 $seen[$key] = false;
1743 return $out;
1744 case "list":
1745 foreach ($value[2] as &$item) {
1746 $item = $this->reduce($item, $forExpression);
1747 }
1748 return $value;
1749 case "expression":
1750 return $this->evaluate($value);
1751 case "string":
1752 foreach ($value[2] as &$part) {
1753 if (is_array($part)) {
1754 $strip = $part[0] == "variable";
1755 $part = $this->reduce($part);
1756 if ($strip) {
1757 $part = $this->lib_e($part);
1758 }
1759 }
1760 }
1761 return $value;
1762 case "escape":
1763 list(, $inner) = $value;
1764 return $this->lib_e($this->reduce($inner));
1765 case "function":
1766 $color = $this->funcToColor($value);
1767 if ($color) {
1768 return $color;
1769 }
1770
1771 list(, $name, $args) = $value;
1772 if ($name == "%") {
1773 $name = "_sprintf";
1774 }
1775
1776 $f = isset($this->libFunctions[$name]) ?
1777 $this->libFunctions[$name] : array($this, 'lib_'.str_replace('-', '_', $name));
1778
1779 if (is_callable($f)) {
1780 if ($args[0] == 'list') {
1781 $args = self::compressList($args[2], $args[1]);
1782 }
1783
1784 $ret = call_user_func($f, $this->reduce($args, true), $this);
1785
1786 if (is_null($ret)) {
1787 return array("string", "", array(
1788 $name, "(", $args, ")"
1789 ));
1790 }
1791
1792 // convert to a typed value if the result is a php primitive
1793 if (is_numeric($ret)) {
1794 $ret = array('number', $ret, "");
1795 } elseif (!is_array($ret)) {
1796 $ret = array('keyword', $ret);
1797 }
1798
1799 return $ret;
1800 }
1801
1802 // plain function, reduce args
1803 $value[2] = $this->reduce($value[2]);
1804 return $value;
1805 case "unary":
1806 list(, $op, $exp) = $value;
1807 $exp = $this->reduce($exp);
1808
1809 if ($exp[0] == "number") {
1810 switch ($op) {
1811 case "+":
1812 return $exp;
1813 case "-":
1814 $exp[1] *= -1;
1815 return $exp;
1816 }
1817 }
1818 return array("string", "", array($op, $exp));
1819 }
1820
1821 if ($forExpression) {
1822 switch ($value[0]) {
1823 case "keyword":
1824 if ($color = $this->coerceColor($value)) {
1825 return $color;
1826 }
1827 break;
1828 case "raw_color":
1829 return $this->coerceColor($value);
1830 }
1831 }
1832
1833 return $value;
1834 }
1835
1836
1837 // coerce a value for use in color operation
1838 protected function coerceColor($value)
1839 {
1840 switch ($value[0]) {
1841 case 'color':
1842 return $value;
1843 case 'raw_color':
1844 $c = array("color", 0, 0, 0);
1845 $colorStr = substr($value[1], 1);
1846 $num = hexdec($colorStr);
1847 $width = strlen($colorStr) == 3 ? 16 : 256;
1848
1849 for ($i = 3; $i > 0; $i--) { // 3 2 1
1850 $t = intval($num) % $width;
1851 $num /= $width;
1852
1853 $c[$i] = $t * (256 / $width) + $t * floor(16/$width);
1854 }
1855
1856 return $c;
1857 case 'keyword':
1858 $name = $value[1];
1859 if (isset(self::$cssColors[$name])) {
1860 $rgba = explode(',', self::$cssColors[$name]);
1861
1862 if (isset($rgba[3])) {
1863 return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1864 }
1865 return array('color', $rgba[0], $rgba[1], $rgba[2]);
1866 }
1867 return null;
1868 }
1869 return null;
1870 }
1871
1872 // make something string like into a string
1873 protected function coerceString($value)
1874 {
1875 switch ($value[0]) {
1876 case "string":
1877 return $value;
1878 case "keyword":
1879 return array("string", "", array($value[1]));
1880 }
1881 return null;
1882 }
1883
1884 // turn list of length 1 into value type
1885 protected function flattenList($value)
1886 {
1887 if ($value[0] == "list" && count($value[2]) == 1) {
1888 return $this->flattenList($value[2][0]);
1889 }
1890 return $value;
1891 }
1892
1893 public function toBool($a)
1894 {
1895 return $a ? self::$TRUE : self::$FALSE;
1896 }
1897
1898 // evaluate an expression
1899 protected function evaluate($exp)
1900 {
1901 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1902
1903 $left = $this->reduce($left, true);
1904 $right = $this->reduce($right, true);
1905
1906 if ($leftColor = $this->coerceColor($left)) {
1907 $left = $leftColor;
1908 }
1909
1910 if ($rightColor = $this->coerceColor($right)) {
1911 $right = $rightColor;
1912 }
1913
1914 $ltype = $left[0];
1915 $rtype = $right[0];
1916
1917 // operators that work on all types
1918 if ($op == "and") {
1919 return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
1920 }
1921
1922 if ($op == "=") {
1923 return $this->toBool($this->eq($left, $right));
1924 }
1925
1926 if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1927 return $str;
1928 }
1929
1930 // type based operators
1931 $fname = "op_{$ltype}_{$rtype}";
1932 if (is_callable(array($this, $fname))) {
1933 $out = $this->$fname($op, $left, $right);
1934 if (!is_null($out)) {
1935 return $out;
1936 }
1937 }
1938
1939 // make the expression look it did before being parsed
1940 $paddedOp = $op;
1941 if ($whiteBefore) {
1942 $paddedOp = " ".$paddedOp;
1943 }
1944 if ($whiteAfter) {
1945 $paddedOp .= " ";
1946 }
1947
1948 return array("string", "", array($left, $paddedOp, $right));
1949 }
1950
1951 protected function stringConcatenate($left, $right)
1952 {
1953 if ($strLeft = $this->coerceString($left)) {
1954 if ($right[0] == "string") {
1955 $right[1] = "";
1956 }
1957 $strLeft[2][] = $right;
1958 return $strLeft;
1959 }
1960
1961 if ($strRight = $this->coerceString($right)) {
1962 array_unshift($strRight[2], $left);
1963 return $strRight;
1964 }
1965 return '';
1966 }
1967
1968
1969 // make sure a color's components don't go out of bounds
1970 protected function fixColor($c)
1971 {
1972 foreach (range(1, 3) as $i) {
1973 if ($c[$i] < 0) {
1974 $c[$i] = 0;
1975 }
1976 if ($c[$i] > 255) {
1977 $c[$i] = 255;
1978 }
1979 }
1980
1981 return $c;
1982 }
1983
1984 protected function op_number_color($op, $lft, $rgt)
1985 {
1986 if ($op == '+' || $op == '*') {
1987 return $this->op_color_number($op, $rgt, $lft);
1988 }
1989 return array();
1990 }
1991
1992 protected function op_color_number($op, $lft, $rgt)
1993 {
1994 if ($rgt[0] == '%') {
1995 $rgt[1] /= 100;
1996 }
1997
1998 return $this->op_color_color(
1999 $op,
2000 $lft,
2001 array_fill(1, count($lft) - 1, $rgt[1])
2002 );
2003 }
2004
2005 protected function op_color_color($op, $left, $right)
2006 {
2007 $out = array('color');
2008 $max = count($left) > count($right) ? count($left) : count($right);
2009 foreach (range(1, $max - 1) as $i) {
2010 $lval = isset($left[$i]) ? $left[$i] : 0;
2011 $rval = isset($right[$i]) ? $right[$i] : 0;
2012 switch ($op) {
2013 case '+':
2014 $out[] = $lval + $rval;
2015 break;
2016 case '-':
2017 $out[] = $lval - $rval;
2018 break;
2019 case '*':
2020 $out[] = $lval * $rval;
2021 break;
2022 case '%':
2023 $out[] = $lval % $rval;
2024 break;
2025 case '/':
2026 if ($rval == 0) {
2027 $this->throwError("evaluate error: can't divide by zero");
2028 }
2029 $out[] = $lval / $rval;
2030 break;
2031 default:
2032 $this->throwError('evaluate error: color op number failed on op '.$op);
2033 }
2034 }
2035 return $this->fixColor($out);
2036 }
2037
2038 public function lib_red($color)
2039 {
2040 $color = $this->coerceColor($color);
2041 if (is_null($color)) {
2042 $this->throwError('color expected for red()');
2043 }
2044
2045 return $color[1];
2046 }
2047
2048 public function lib_green($color)
2049 {
2050 $color = $this->coerceColor($color);
2051 if (is_null($color)) {
2052 $this->throwError('color expected for green()');
2053 }
2054
2055 return $color[2];
2056 }
2057
2058 public function lib_blue($color)
2059 {
2060 $color = $this->coerceColor($color);
2061 if (is_null($color)) {
2062 $this->throwError('color expected for blue()');
2063 }
2064
2065 return $color[3];
2066 }
2067
2068
2069 // operator on two numbers
2070 protected function op_number_number($op, $left, $right)
2071 {
2072 $unit = empty($left[2]) ? $right[2] : $left[2];
2073
2074 $value = 0;
2075 switch ($op) {
2076 case '+':
2077 $value = $left[1] + $right[1];
2078 break;
2079 case '*':
2080 $value = $left[1] * $right[1];
2081 break;
2082 case '-':
2083 $value = $left[1] - $right[1];
2084 break;
2085 case '%':
2086 $value = $left[1] % $right[1];
2087 break;
2088 case '/':
2089 if ($right[1] == 0) {
2090 $this->throwError('parse error: divide by zero');
2091 }
2092 $value = $left[1] / $right[1];
2093 break;
2094 case '<':
2095 return $this->toBool($left[1] < $right[1]);
2096 case '>':
2097 return $this->toBool($left[1] > $right[1]);
2098 case '>=':
2099 return $this->toBool($left[1] >= $right[1]);
2100 case '=<':
2101 return $this->toBool($left[1] <= $right[1]);
2102 default:
2103 $this->throwError('parse error: unknown number operator: '.$op);
2104 }
2105
2106 return array("number", $value, $unit);
2107 }
2108
2109
2110 /* environment functions */
2111
2112 protected function makeOutputBlock($type, $selectors = null)
2113 {
2114 $b = new stdclass();
2115 $b->lines = array();
2116 $b->children = array();
2117 $b->selectors = $selectors;
2118 $b->type = $type;
2119 $b->parent = $this->scope;
2120 return $b;
2121 }
2122
2123 // the state of execution
2124 protected function pushEnv($block = null)
2125 {
2126 $e = new stdclass();
2127 $e->parent = $this->env;
2128 $e->store = array();
2129 $e->block = $block;
2130
2131 $this->env = $e;
2132 return $e;
2133 }
2134
2135 // pop something off the stack
2136 protected function popEnv()
2137 {
2138 $old = $this->env;
2139 $this->env = $this->env->parent;
2140 return $old;
2141 }
2142
2143 // set something in the current env
2144 protected function set($name, $value)
2145 {
2146 $this->env->store[$name] = $value;
2147 }
2148
2149
2150 // get the highest occurrence entry for a name
2151 protected function get($name)
2152 {
2153 $current = $this->env;
2154
2155 $isArguments = $name == $this->vPrefix.'arguments';
2156 while ($current) {
2157 if ($isArguments && isset($current->arguments)) {
2158 return array('list', ' ', $current->arguments);
2159 }
2160
2161 if (isset($current->store[$name])) {
2162 return $current->store[$name];
2163 }
2164
2165 $current = isset($current->storeParent) ?
2166 $current->storeParent : $current->parent;
2167 }
2168
2169 $this->throwError("variable $name is undefined");
2170 }
2171
2172 // inject array of unparsed strings into environment as variables
2173 protected function injectVariables($args)
2174 {
2175 $this->pushEnv();
2176 $parser = new lessc_parser($this, __METHOD__);
2177 $value = null;
2178 foreach ($args as $name => $strValue) {
2179 if ($name[0] !== '@') {
2180 $name = '@'.$name;
2181 }
2182 $parser->count = 0;
2183 $parser->buffer = (string) $strValue;
2184 if (!$parser->propertyValue($value)) {
2185 throw new Exception("failed to parse passed in variable $name: $strValue");
2186 }
2187
2188 $this->set($name, $value);
2189 }
2190 }
2191
2196 public function __construct($fname = null)
2197 {
2198 if ($fname !== null) {
2199 // used for deprecated parse method
2200 $this->_parseFile = $fname;
2201 }
2202 }
2203
2204 public function compile($string, $name = null)
2205 {
2206 $locale = setlocale(LC_NUMERIC, '0');
2207 setlocale(LC_NUMERIC, "C");
2208
2209 $this->parser = $this->makeParser($name);
2210 $root = $this->parser->parse($string);
2211
2212 $this->env = null;
2213 $this->scope = null;
2214
2215 $this->formatter = $this->newFormatter();
2216
2217 if (!empty($this->registeredVars)) {
2218 $this->injectVariables($this->registeredVars);
2219 }
2220
2221 $this->sourceParser = $this->parser; // used for error messages
2222 $this->compileBlock($root);
2223
2224 ob_start();
2225 $this->formatter->block($this->scope);
2226 $out = ob_get_clean();
2227 setlocale(LC_NUMERIC, $locale);
2228 return $out;
2229 }
2230
2231 public function compileFile($fname, $outFname = null)
2232 {
2233 if (!is_readable($fname)) {
2234 throw new Exception('load error: failed to find '.$fname);
2235 }
2236
2237 $pi = pathinfo($fname);
2238
2239 $oldImport = $this->importDir;
2240
2241 $this->importDir = (array) $this->importDir;
2242 $this->importDir[] = $pi['dirname'].'/';
2243
2244 $this->addParsedFile($fname);
2245
2246 $out = $this->compile(file_get_contents($fname), $fname);
2247
2248 $this->importDir = $oldImport;
2249
2250 if ($outFname !== null) {
2251 return file_put_contents($outFname, $out);
2252 }
2253
2254 return $out;
2255 }
2256
2257 // compile only if changed input has changed or output doesn't exist
2258 public function checkedCompile($in, $out)
2259 {
2260 if (!is_file($out) || filemtime($in) > filemtime($out)) {
2261 $this->compileFile($in, $out);
2262 return true;
2263 }
2264 return false;
2265 }
2266
2287 public function cachedCompile($in, $force = false)
2288 {
2289 // assume no root
2290 $root = null;
2291
2292 if (is_string($in)) {
2293 $root = $in;
2294 } elseif (is_array($in) && isset($in['root'])) {
2295 if ($force || !isset($in['files'])) {
2296 // If we are forcing a recompile or if for some reason the
2297 // structure does not contain any file information we should
2298 // specify the root to trigger a rebuild.
2299 $root = $in['root'];
2300 } elseif (isset($in['files']) && is_array($in['files'])) {
2301 foreach ($in['files'] as $fname => $ftime) {
2302 if (!file_exists($fname) || filemtime($fname) > $ftime) {
2303 // One of the files we knew about previously has changed
2304 // so we should look at our incoming root again.
2305 $root = $in['root'];
2306 break;
2307 }
2308 }
2309 }
2310 } else {
2311 // TODO: Throw an exception? We got neither a string nor something
2312 // that looks like a compatible lessphp cache structure.
2313 return null;
2314 }
2315
2316 if ($root !== null) {
2317 // If we have a root value which means we should rebuild.
2318 $out = array();
2319 $out['root'] = $root;
2320 $out['compiled'] = $this->compileFile($root);
2321 $out['files'] = $this->allParsedFiles();
2322 $out['updated'] = time();
2323 return $out;
2324 } else {
2325 // No changes, pass back the structure
2326 // we were given initially.
2327 return $in;
2328 }
2329 }
2330
2331 // parse and compile buffer
2332 // This is deprecated
2333 public function parse($str = null, $initialVariables = null)
2334 {
2335 if (is_array($str)) {
2336 $initialVariables = $str;
2337 $str = null;
2338 }
2339
2340 $oldVars = $this->registeredVars;
2341 if ($initialVariables !== null) {
2342 $this->setVariables($initialVariables);
2343 }
2344
2345 if ($str == null) {
2346 if (empty($this->_parseFile)) {
2347 throw new exception("nothing to parse");
2348 }
2349
2350 $out = $this->compileFile($this->_parseFile);
2351 } else {
2352 $out = $this->compile($str);
2353 }
2354
2355 $this->registeredVars = $oldVars;
2356 return $out;
2357 }
2358
2359 protected function makeParser($name)
2360 {
2361 $parser = new lessc_parser($this, $name);
2362 $parser->writeComments = $this->preserveComments;
2363
2364 return $parser;
2365 }
2366
2367 public function setFormatter($name)
2368 {
2369 $this->formatterName = $name;
2370 }
2371
2372 protected function newFormatter()
2373 {
2374 $className = "lessc_formatter_lessjs";
2375 if (!empty($this->formatterName)) {
2376 if (!is_string($this->formatterName)) {
2377 return $this->formatterName;
2378 }
2379 $className = "lessc_formatter_$this->formatterName";
2380 }
2381
2382 return new $className();
2383 }
2384
2385 public function setPreserveComments($preserve)
2386 {
2387 $this->preserveComments = $preserve;
2388 }
2389
2390 public function registerFunction($name, $func)
2391 {
2392 $this->libFunctions[$name] = $func;
2393 }
2394
2395 public function unregisterFunction($name)
2396 {
2397 unset($this->libFunctions[$name]);
2398 }
2399
2400 public function setVariables($variables)
2401 {
2402 $this->registeredVars = array_merge($this->registeredVars, $variables);
2403 }
2404
2405 public function unsetVariable($name)
2406 {
2407 unset($this->registeredVars[$name]);
2408 }
2409
2410 public function setImportDir($dirs)
2411 {
2412 $this->importDir = (array) $dirs;
2413 }
2414
2415 public function addImportDir($dir)
2416 {
2417 $this->importDir = (array) $this->importDir;
2418 $this->importDir[] = $dir;
2419 }
2420
2421 public function allParsedFiles()
2422 {
2423 return $this->allParsedFiles;
2424 }
2425
2426 public function addParsedFile($file)
2427 {
2428 $this->allParsedFiles[realpath($file)] = filemtime($file);
2429 }
2430
2434 public function throwError($msg = null)
2435 {
2436 if ($this->sourceLoc >= 0) {
2437 $this->sourceParser->throwError($msg, $this->sourceLoc);
2438 }
2439 throw new exception($msg);
2440 }
2441
2442 // compile file $in to file $out if $in is newer than $out
2443 // returns true when it compiles, false otherwise
2444 public static function ccompile($in, $out, $less = null)
2445 {
2446 if ($less === null) {
2447 $less = new self();
2448 }
2449 return $less->checkedCompile($in, $out);
2450 }
2451
2452 public static function cexecute($in, $force = false, $less = null)
2453 {
2454 if ($less === null) {
2455 $less = new self();
2456 }
2457 return $less->cachedCompile($in, $force);
2458 }
2459
2460 protected static $cssColors = array(
2461 'aliceblue' => '240,248,255',
2462 'antiquewhite' => '250,235,215',
2463 'aqua' => '0,255,255',
2464 'aquamarine' => '127,255,212',
2465 'azure' => '240,255,255',
2466 'beige' => '245,245,220',
2467 'bisque' => '255,228,196',
2468 'black' => '0,0,0',
2469 'blanchedalmond' => '255,235,205',
2470 'blue' => '0,0,255',
2471 'blueviolet' => '138,43,226',
2472 'brown' => '165,42,42',
2473 'burlywood' => '222,184,135',
2474 'cadetblue' => '95,158,160',
2475 'chartreuse' => '127,255,0',
2476 'chocolate' => '210,105,30',
2477 'coral' => '255,127,80',
2478 'cornflowerblue' => '100,149,237',
2479 'cornsilk' => '255,248,220',
2480 'crimson' => '220,20,60',
2481 'cyan' => '0,255,255',
2482 'darkblue' => '0,0,139',
2483 'darkcyan' => '0,139,139',
2484 'darkgoldenrod' => '184,134,11',
2485 'darkgray' => '169,169,169',
2486 'darkgreen' => '0,100,0',
2487 'darkgrey' => '169,169,169',
2488 'darkkhaki' => '189,183,107',
2489 'darkmagenta' => '139,0,139',
2490 'darkolivegreen' => '85,107,47',
2491 'darkorange' => '255,140,0',
2492 'darkorchid' => '153,50,204',
2493 'darkred' => '139,0,0',
2494 'darksalmon' => '233,150,122',
2495 'darkseagreen' => '143,188,143',
2496 'darkslateblue' => '72,61,139',
2497 'darkslategray' => '47,79,79',
2498 'darkslategrey' => '47,79,79',
2499 'darkturquoise' => '0,206,209',
2500 'darkviolet' => '148,0,211',
2501 'deeppink' => '255,20,147',
2502 'deepskyblue' => '0,191,255',
2503 'dimgray' => '105,105,105',
2504 'dimgrey' => '105,105,105',
2505 'dodgerblue' => '30,144,255',
2506 'firebrick' => '178,34,34',
2507 'floralwhite' => '255,250,240',
2508 'forestgreen' => '34,139,34',
2509 'fuchsia' => '255,0,255',
2510 'gainsboro' => '220,220,220',
2511 'ghostwhite' => '248,248,255',
2512 'gold' => '255,215,0',
2513 'goldenrod' => '218,165,32',
2514 'gray' => '128,128,128',
2515 'green' => '0,128,0',
2516 'greenyellow' => '173,255,47',
2517 'grey' => '128,128,128',
2518 'honeydew' => '240,255,240',
2519 'hotpink' => '255,105,180',
2520 'indianred' => '205,92,92',
2521 'indigo' => '75,0,130',
2522 'ivory' => '255,255,240',
2523 'khaki' => '240,230,140',
2524 'lavender' => '230,230,250',
2525 'lavenderblush' => '255,240,245',
2526 'lawngreen' => '124,252,0',
2527 'lemonchiffon' => '255,250,205',
2528 'lightblue' => '173,216,230',
2529 'lightcoral' => '240,128,128',
2530 'lightcyan' => '224,255,255',
2531 'lightgoldenrodyellow' => '250,250,210',
2532 'lightgray' => '211,211,211',
2533 'lightgreen' => '144,238,144',
2534 'lightgrey' => '211,211,211',
2535 'lightpink' => '255,182,193',
2536 'lightsalmon' => '255,160,122',
2537 'lightseagreen' => '32,178,170',
2538 'lightskyblue' => '135,206,250',
2539 'lightslategray' => '119,136,153',
2540 'lightslategrey' => '119,136,153',
2541 'lightsteelblue' => '176,196,222',
2542 'lightyellow' => '255,255,224',
2543 'lime' => '0,255,0',
2544 'limegreen' => '50,205,50',
2545 'linen' => '250,240,230',
2546 'magenta' => '255,0,255',
2547 'maroon' => '128,0,0',
2548 'mediumaquamarine' => '102,205,170',
2549 'mediumblue' => '0,0,205',
2550 'mediumorchid' => '186,85,211',
2551 'mediumpurple' => '147,112,219',
2552 'mediumseagreen' => '60,179,113',
2553 'mediumslateblue' => '123,104,238',
2554 'mediumspringgreen' => '0,250,154',
2555 'mediumturquoise' => '72,209,204',
2556 'mediumvioletred' => '199,21,133',
2557 'midnightblue' => '25,25,112',
2558 'mintcream' => '245,255,250',
2559 'mistyrose' => '255,228,225',
2560 'moccasin' => '255,228,181',
2561 'navajowhite' => '255,222,173',
2562 'navy' => '0,0,128',
2563 'oldlace' => '253,245,230',
2564 'olive' => '128,128,0',
2565 'olivedrab' => '107,142,35',
2566 'orange' => '255,165,0',
2567 'orangered' => '255,69,0',
2568 'orchid' => '218,112,214',
2569 'palegoldenrod' => '238,232,170',
2570 'palegreen' => '152,251,152',
2571 'paleturquoise' => '175,238,238',
2572 'palevioletred' => '219,112,147',
2573 'papayawhip' => '255,239,213',
2574 'peachpuff' => '255,218,185',
2575 'peru' => '205,133,63',
2576 'pink' => '255,192,203',
2577 'plum' => '221,160,221',
2578 'powderblue' => '176,224,230',
2579 'purple' => '128,0,128',
2580 'red' => '255,0,0',
2581 'rosybrown' => '188,143,143',
2582 'royalblue' => '65,105,225',
2583 'saddlebrown' => '139,69,19',
2584 'salmon' => '250,128,114',
2585 'sandybrown' => '244,164,96',
2586 'seagreen' => '46,139,87',
2587 'seashell' => '255,245,238',
2588 'sienna' => '160,82,45',
2589 'silver' => '192,192,192',
2590 'skyblue' => '135,206,235',
2591 'slateblue' => '106,90,205',
2592 'slategray' => '112,128,144',
2593 'slategrey' => '112,128,144',
2594 'snow' => '255,250,250',
2595 'springgreen' => '0,255,127',
2596 'steelblue' => '70,130,180',
2597 'tan' => '210,180,140',
2598 'teal' => '0,128,128',
2599 'thistle' => '216,191,216',
2600 'tomato' => '255,99,71',
2601 'transparent' => '0,0,0,0',
2602 'turquoise' => '64,224,208',
2603 'violet' => '238,130,238',
2604 'wheat' => '245,222,179',
2605 'white' => '255,255,255',
2606 'whitesmoke' => '245,245,245',
2607 'yellow' => '255,255,0',
2608 'yellowgreen' => '154,205,50'
2609 );
2610}
2611
2612// responsible for taking a string of LESS code and converting it into a
2613// syntax tree
2615{
2616 protected static $nextBlockId = 0; // used to uniquely identify blocks
2617
2618 protected static $precedence = array(
2619 '=<' => 0,
2620 '>=' => 0,
2621 '=' => 0,
2622 '<' => 0,
2623 '>' => 0,
2624
2625 '+' => 1,
2626 '-' => 1,
2627 '*' => 2,
2628 '/' => 2,
2629 '%' => 2,
2630 );
2631
2632 protected static $whitePattern;
2633 protected static $commentMulti;
2634
2635 protected static $commentSingle = "//";
2636 protected static $commentMultiLeft = "/*";
2637 protected static $commentMultiRight = "*/";
2638
2639 // regex string to match any of the operators
2640 protected static $operatorString;
2641
2642 // these properties will supress division unless it's inside parenthases
2643 protected static $supressDivisionProps =
2644 array('/border-radius$/i', '/^font$/i');
2645
2646 protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
2647 protected $lineDirectives = array("charset");
2648
2658 protected $inParens = false;
2659
2660 // caches preg escaped literals
2661 protected static $literalCache = array();
2662
2663 public $env;
2664 public $buffer;
2665 public $count;
2666 public $line;
2667 public $eatWhiteDefault;
2668 public $lessc;
2669 public $sourceName;
2670 public $writeComments;
2671 public $seenComments;
2672 public $currentProperty;
2673 public $inExp;
2674
2675
2676 public function __construct($lessc, $sourceName = null)
2677 {
2678 $this->eatWhiteDefault = true;
2679 // reference to less needed for vPrefix, mPrefix, and parentSelector
2680 $this->lessc = $lessc;
2681
2682 $this->sourceName = $sourceName; // name used for error messages
2683
2684 $this->writeComments = false;
2685
2686 if (!self::$operatorString) {
2687 self::$operatorString =
2688 '('.implode('|', array_map(
2689 array('lessc', 'preg_quote'),
2690 array_keys(self::$precedence)
2691 )).')';
2692
2693 $commentSingle = Lessc::preg_quote(self::$commentSingle);
2694 $commentMultiLeft = Lessc::preg_quote(self::$commentMultiLeft);
2695 $commentMultiRight = Lessc::preg_quote(self::$commentMultiRight);
2696
2697 self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
2698 self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
2699 }
2700 }
2701
2709 public function parse($buffer)
2710 {
2711 $this->count = 0;
2712 $this->line = 1;
2713
2714 $this->env = null; // block stack
2715 $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
2716 $this->pushSpecialBlock("root");
2717 $this->eatWhiteDefault = true;
2718 $this->seenComments = array();
2719
2720 // trim whitespace on head
2721 // if (preg_match('/^\s+/', $this->buffer, $m)) {
2722 // $this->line += substr_count($m[0], "\n");
2723 // $this->buffer = ltrim($this->buffer);
2724 // }
2725 $this->whitespace();
2726
2727 // parse the entire file
2728 while (false !== $this->parseChunk());
2729
2730 if ($this->count != strlen($this->buffer)) {
2731 $this->throwError('parse error count '.$this->count.' != len buffer '.strlen($this->buffer));
2732
2733 }
2734
2735 // TODO report where the block was opened
2736 if (!property_exists($this->env, 'parent') || !is_null($this->env->parent)) {
2737 throw new exception('parse error: unclosed block');
2738 }
2739
2740 return $this->env;
2741 }
2742
2779 protected function parseChunk()
2780 {
2781 if (empty($this->buffer)) {
2782 return false;
2783 }
2784 $s = $this->seek();
2785
2786 if ($this->whitespace()) {
2787 return true;
2788 }
2789
2790 $key = null;
2791 $value = null;
2792 $mediaQueries = null;
2793 $dirName = null;
2794 $dirValue = null;
2795 $importValue = null;
2796 $guards = null;
2797 $tag = null;
2798 $args = null;
2799 $isVararg = null;
2800 $argv = null;
2801 $suffix = null;
2802 $var = null;
2803 $tags = null;
2804
2805 // setting a property
2806 if ($this->keyword($key) && $this->assign() &&
2807 $this->propertyValue($value, $key) && $this->end()
2808 ) {
2809 $this->append(array('assign', $key, $value), $s);
2810 return true;
2811 } else {
2812 $this->seek($s);
2813 }
2814
2815
2816 // look for special css blocks
2817 if ($this->literal('@', false)) {
2818 $this->count--;
2819
2820 // media
2821 if ($this->literal('@media')) {
2822 if ($this->mediaQueryList($mediaQueries)
2823 && $this->literal('{')
2824 ) {
2825 $media = $this->pushSpecialBlock("media");
2826 $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
2827 return true;
2828 } else {
2829 $this->seek($s);
2830 return false;
2831 }
2832 }
2833
2834 if ($this->literal("@", false) && $this->keyword($dirName)) {
2835 if ($this->isDirective($dirName, $this->blockDirectives)) {
2836 if ($this->openString("{", $dirValue, null, array(";")) &&
2837 $this->literal("{")
2838 ) {
2839 $dir = $this->pushSpecialBlock("directive");
2840 $dir->name = $dirName;
2841 if (isset($dirValue)) {
2842 $dir->value = $dirValue;
2843 }
2844 return true;
2845 }
2846 } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
2847 if ($this->propertyValue($dirValue) && $this->end()) {
2848 $this->append(array("directive", $dirName, $dirValue));
2849 return true;
2850 }
2851 }
2852 }
2853
2854 $this->seek($s);
2855 }
2856
2857 // setting a variable
2858 if ($this->variable($var) && $this->assign() &&
2859 $this->propertyValue($value) && $this->end()
2860 ) {
2861 $this->append(array('assign', $var, $value), $s);
2862 return true;
2863 } else {
2864 $this->seek($s);
2865 }
2866
2867 if ($this->import($importValue)) {
2868 $this->append($importValue, $s);
2869 return true;
2870 }
2871
2872 // opening parametric mixin
2873 if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
2874 $this->guards($guards) &&
2875 $this->literal('{')
2876 ) {
2877 $block = $this->pushBlock($this->fixTags(array($tag)));
2878 $block->args = $args;
2879 $block->isVararg = $isVararg;
2880 if (!empty($guards)) {
2881 $block->guards = $guards;
2882 }
2883 return true;
2884 } else {
2885 $this->seek($s);
2886 }
2887
2888 // opening a simple block
2889 if ($this->tags($tags) && $this->literal('{', false)) {
2890 $tags = $this->fixTags($tags);
2891 $this->pushBlock($tags);
2892 return true;
2893 } else {
2894 $this->seek($s);
2895 }
2896
2897 // closing a block
2898 if ($this->literal('}', false)) {
2899 try {
2900 $block = $this->pop();
2901 } catch (exception $e) {
2902 $this->seek($s);
2903 $this->throwError($e->getMessage());
2904 }
2905
2906 $hidden = false;
2907 if (is_null($block->type)) {
2908 $hidden = true;
2909 if (!isset($block->args)) {
2910 foreach ($block->tags as $tag) {
2911 if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
2912 $hidden = false;
2913 break;
2914 }
2915 }
2916 }
2917
2918 foreach ($block->tags as $tag) {
2919 if (is_string($tag)) {
2920 $this->env->children[$tag][] = $block;
2921 }
2922 }
2923 }
2924
2925 if (!$hidden) {
2926 $this->append(array('block', $block), $s);
2927 }
2928
2929 // this is done here so comments aren't bundled into he block that
2930 // was just closed
2931 $this->whitespace();
2932 return true;
2933 }
2934
2935 // mixin
2936 if ($this->mixinTags($tags) &&
2937 $this->argumentDef($argv, $isVararg) &&
2938 $this->keyword($suffix) && $this->end()
2939 ) {
2940 $tags = $this->fixTags($tags);
2941 $this->append(array('mixin', $tags, $argv, $suffix), $s);
2942 return true;
2943 } else {
2944 $this->seek($s);
2945 }
2946
2947 // spare ;
2948 if ($this->literal(';')) {
2949 return true;
2950 }
2951
2952 return false; // got nothing, throw error
2953 }
2954
2955 protected function isDirective($dirname, $directives)
2956 {
2957 // TODO: cache pattern in parser
2958 $pattern = implode(
2959 "|",
2960 array_map(array("lessc", "preg_quote"), $directives)
2961 );
2962 $pattern = '/^(-[a-z-]+-)?('.$pattern.')$/i';
2963
2964 return preg_match($pattern, $dirname);
2965 }
2966
2967 protected function fixTags($tags)
2968 {
2969 // move @ tags out of variable namespace
2970 foreach ($tags as &$tag) {
2971 if ($tag[0] == $this->lessc->vPrefix) {
2972 $tag[0] = $this->lessc->mPrefix;
2973 }
2974 }
2975 return $tags;
2976 }
2977
2978 // a list of expressions
2979 protected function expressionList(&$exps)
2980 {
2981 $exp = null;
2982
2983 $values = array();
2984
2985 while ($this->expression($exp)) {
2986 $values[] = $exp;
2987 }
2988
2989 if (count($values) == 0) {
2990 return false;
2991 }
2992
2993 $exps = Lessc::compressList($values, ' ');
2994 return true;
2995 }
2996
3001 protected function expression(&$out)
3002 {
3003 $lhs = null;
3004 $rhs = null;
3005
3006 if ($this->value($lhs)) {
3007 $out = $this->expHelper($lhs, 0);
3008
3009 // look for / shorthand
3010 if (!empty($this->env->supressedDivision)) {
3011 unset($this->env->supressedDivision);
3012 $s = $this->seek();
3013 if ($this->literal("/") && $this->value($rhs)) {
3014 $out = array("list", "",
3015 array($out, array("keyword", "/"), $rhs));
3016 } else {
3017 $this->seek($s);
3018 }
3019 }
3020
3021 return true;
3022 }
3023 return false;
3024 }
3025
3029 protected function expHelper($lhs, $minP)
3030 {
3031 $next = null;
3032 $rhs = null;
3033
3034 $this->inExp = true;
3035 $ss = $this->seek();
3036
3037 while (true) {
3038 $whiteBefore = isset($this->buffer[$this->count - 1]) &&
3039 ctype_space($this->buffer[$this->count - 1]);
3040
3041 // If there is whitespace before the operator, then we require
3042 // whitespace after the operator for it to be an expression
3043 $needWhite = $whiteBefore && !$this->inParens;
3044
3045 $m = array();
3046 if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
3047 if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
3048 foreach (self::$supressDivisionProps as $pattern) {
3049 if (preg_match($pattern, $this->env->currentProperty)) {
3050 $this->env->supressedDivision = true;
3051 break 2;
3052 }
3053 }
3054 }
3055
3056
3057 $whiteAfter = isset($this->buffer[$this->count - 1]) &&
3058 ctype_space($this->buffer[$this->count - 1]);
3059
3060 if (!$this->value($rhs)) {
3061 break;
3062 }
3063
3064 // peek for next operator to see what to do with rhs
3065 if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
3066 $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
3067 }
3068
3069 $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
3070 $ss = $this->seek();
3071
3072 continue;
3073 }
3074
3075 break;
3076 }
3077
3078 $this->seek($ss);
3079
3080 return $lhs;
3081 }
3082
3083 // consume a list of values for a property
3084 public function propertyValue(&$value, $keyName = null)
3085 {
3086 $v = null;
3087 $values = array();
3088
3089 if ($keyName !== null) {
3090 $this->env->currentProperty = $keyName;
3091 }
3092
3093 $s = null;
3094 while ($this->expressionList($v)) {
3095 $values[] = $v;
3096 $s = $this->seek();
3097 if (!$this->literal(',')) {
3098 break;
3099 }
3100 }
3101
3102 if ($s) {
3103 $this->seek($s);
3104 }
3105
3106 if ($keyName !== null) {
3107 unset($this->env->currentProperty);
3108 }
3109
3110 if (count($values) == 0) {
3111 return false;
3112 }
3113
3114 $value = Lessc::compressList($values, ', ');
3115 return true;
3116 }
3117
3118 protected function parenValue(&$out)
3119 {
3120 $exp = null;
3121
3122 $s = $this->seek();
3123
3124 // speed shortcut
3125 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
3126 return false;
3127 }
3128
3130 if ($this->literal("(") &&
3131 ($this->inParens = true) && $this->expression($exp) &&
3132 $this->literal(")")
3133 ) {
3134 $out = $exp;
3135 $this->inParens = $inParens;
3136 return true;
3137 } else {
3138 $this->inParens = $inParens;
3139 $this->seek($s);
3140 }
3141
3142 return false;
3143 }
3144
3145 // a single value
3146 protected function value(&$value)
3147 {
3148 $inner = null;
3149 $word = null;
3150 $str = null;
3151 $var = null;
3152
3153 $s = $this->seek();
3154
3155 // speed shortcut
3156 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
3157 // negation
3158 if ($this->literal("-", false) &&
3159 (($this->variable($inner) && $inner = array("variable", $inner)) ||
3160 $this->unit($inner) ||
3161 $this->parenValue($inner))
3162 ) {
3163 $value = array("unary", "-", $inner);
3164 return true;
3165 } else {
3166 $this->seek($s);
3167 }
3168 }
3169
3170 if ($this->parenValue($value)) {
3171 return true;
3172 }
3173 if ($this->unit($value)) {
3174 return true;
3175 }
3176 if ($this->color($value)) {
3177 return true;
3178 }
3179 if ($this->func($value)) {
3180 return true;
3181 }
3182 if ($this->string($value)) {
3183 return true;
3184 }
3185
3186 if ($this->keyword($word)) {
3187 $value = array('keyword', $word);
3188 return true;
3189 }
3190
3191 // try a variable
3192 if ($this->variable($var)) {
3193 $value = array('variable', $var);
3194 return true;
3195 }
3196
3197 // unquote string (should this work on any type?
3198 if ($this->literal("~") && $this->string($str)) {
3199 $value = array("escape", $str);
3200 return true;
3201 } else {
3202 $this->seek($s);
3203 }
3204
3205 // css hack: \0
3206 $m = array();
3207 if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
3208 $value = array('keyword', '\\'.$m[1]);
3209 return true;
3210 } else {
3211 $this->seek($s);
3212 }
3213
3214 return false;
3215 }
3216
3217 // an import statement
3218 protected function import(&$out, $value = '')
3219 {
3220 if (!$this->literal('@import')) {
3221 return false;
3222 }
3223
3224 // @import "something.css" media;
3225 // @import url("something.css") media;
3226 // @import url(something.css) media;
3227
3228 if ($this->propertyValue($value)) {
3229 $out = array("import", $value);
3230 return true;
3231 }
3232
3233 return false;
3234 }
3235
3236 protected function mediaQueryList(&$out)
3237 {
3238 $list = null;
3239
3240 if ($this->genericList($list, "mediaQuery", ",", false)) {
3241 $out = $list[2];
3242 return true;
3243 }
3244 return false;
3245 }
3246
3247 protected function mediaQuery(&$out)
3248 {
3249 $mediaType = null;
3250
3251 $s = $this->seek();
3252
3253 $expressions = null;
3254 $parts = array();
3255
3256 if ((($this->literal("only") && ($only = true)) || ($this->literal("not") && ($not = true))) && $this->keyword($mediaType)) {
3257 $prop = array("mediaType");
3258 if (isset($only)) {
3259 $prop[] = "only";
3260 }
3261 if (isset($not)) {
3262 $prop[] = "not";
3263 }
3264 $prop[] = $mediaType;
3265 $parts[] = $prop;
3266 } else {
3267 $this->seek($s);
3268 }
3269
3270
3271 if (!empty($mediaType) && !$this->literal("and")) {
3272 // ~
3273 } else {
3274 $this->genericList($expressions, "mediaExpression", "and", false);
3275 if (is_array($expressions)) {
3276 $parts = array_merge($parts, $expressions[2]);
3277 }
3278 }
3279
3280 if (count($parts) == 0) {
3281 $this->seek($s);
3282 return false;
3283 }
3284
3285 $out = $parts;
3286 return true;
3287 }
3288
3289 protected function mediaExpression(&$out)
3290 {
3291 $feature = null;
3292 $variable = null;
3293
3294 $s = $this->seek();
3295 $value = null;
3296 if ($this->literal("(") &&
3297 $this->keyword($feature) &&
3298 ($this->literal(":") && $this->expression($value)) &&
3299 $this->literal(")")
3300 ) {
3301 $out = array("mediaExp", $feature);
3302 if ($value) {
3303 $out[] = $value;
3304 }
3305 return true;
3306 } elseif ($this->variable($variable)) {
3307 $out = array('variable', $variable);
3308 return true;
3309 }
3310
3311 $this->seek($s);
3312 return false;
3313 }
3314
3315 // an unbounded string stopped by $end
3316 protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null)
3317 {
3318 $str = null;
3319 $inter = null;
3320
3321 $oldWhite = $this->eatWhiteDefault;
3322 $this->eatWhiteDefault = false;
3323
3324 $stop = array("'", '"', "@{", $end);
3325 $stop = array_map(array("lessc", "preg_quote"), $stop);
3326 // $stop[] = self::$commentMulti;
3327
3328 if (!is_null($rejectStrs)) {
3329 $stop = array_merge($stop, $rejectStrs);
3330 }
3331
3332 $patt = '(.*?)('.implode("|", $stop).')';
3333
3334 $nestingLevel = 0;
3335
3336 $content = array();
3337 $m = array();
3338 while ($this->match($patt, $m, false)) {
3339 if (!empty($m[1])) {
3340 $content[] = $m[1];
3341 if ($nestingOpen) {
3342 $nestingLevel += substr_count($m[1], $nestingOpen);
3343 }
3344 }
3345
3346 $tok = $m[2];
3347
3348 $this->count -= strlen($tok);
3349 if ($tok == $end) {
3350 if ($nestingLevel == 0) {
3351 break;
3352 } else {
3353 $nestingLevel--;
3354 }
3355 }
3356
3357 if (($tok == "'" || $tok == '"') && $this->string($str)) {
3358 $content[] = $str;
3359 continue;
3360 }
3361
3362 if ($tok == "@{" && $this->interpolation($inter)) {
3363 $content[] = $inter;
3364 continue;
3365 }
3366
3367 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
3368 break;
3369 }
3370
3371 $content[] = $tok;
3372 $this->count += strlen($tok);
3373 }
3374
3375 $this->eatWhiteDefault = $oldWhite;
3376
3377 if (count($content) == 0) {
3378 return false;
3379 }
3380
3381 // trim the end
3382 if (is_string(end($content))) {
3383 $content[count($content) - 1] = rtrim(end($content));
3384 }
3385
3386 $out = array("string", "", $content);
3387 return true;
3388 }
3389
3390 protected function string(&$out)
3391 {
3392 $inter = null;
3393
3394 $s = $this->seek();
3395 if ($this->literal('"', false)) {
3396 $delim = '"';
3397 } elseif ($this->literal("'", false)) {
3398 $delim = "'";
3399 } else {
3400 return false;
3401 }
3402
3403 $content = array();
3404
3405 // look for either ending delim , escape, or string interpolation
3406 $patt = '([^\n]*?)(@\{|\\\\|'.
3407 Lessc::preg_quote($delim).')';
3408
3409 $oldWhite = $this->eatWhiteDefault;
3410 $this->eatWhiteDefault = false;
3411
3412 $m = array();
3413 while ($this->match($patt, $m, false)) {
3414 $content[] = $m[1];
3415 if ($m[2] == "@{") {
3416 $this->count -= strlen($m[2]);
3417 if ($this->interpolation($inter)) {
3418 $content[] = $inter;
3419 } else {
3420 $this->count += strlen($m[2]);
3421 $content[] = "@{"; // ignore it
3422 }
3423 } elseif ($m[2] == '\\') {
3424 $content[] = $m[2];
3425 if ($this->literal($delim, false)) {
3426 $content[] = $delim;
3427 }
3428 } else {
3429 $this->count -= strlen($delim);
3430 break; // delim
3431 }
3432 }
3433
3434 $this->eatWhiteDefault = $oldWhite;
3435
3436 if ($this->literal($delim)) {
3437 $out = array("string", $delim, $content);
3438 return true;
3439 }
3440
3441 $this->seek($s);
3442 return false;
3443 }
3444
3445 protected function interpolation(&$out)
3446 {
3447 $interp = array();
3448
3449 $oldWhite = $this->eatWhiteDefault;
3450 $this->eatWhiteDefault = true;
3451
3452 $s = $this->seek();
3453 if ($this->literal("@{") &&
3454 $this->openString("}", $interp, null, array("'", '"', ";")) &&
3455 $this->literal("}", false)
3456 ) {
3457 $out = array("interpolate", $interp);
3458 $this->eatWhiteDefault = $oldWhite;
3459 if ($this->eatWhiteDefault) {
3460 $this->whitespace();
3461 }
3462 return true;
3463 }
3464
3465 $this->eatWhiteDefault = $oldWhite;
3466 $this->seek($s);
3467 return false;
3468 }
3469
3470 protected function unit(&$unit)
3471 {
3472 $m = array();
3473
3474 // speed shortcut
3475 if (isset($this->buffer[$this->count])) {
3476 $char = $this->buffer[$this->count];
3477 if (!ctype_digit($char) && $char != ".") {
3478 return false;
3479 }
3480 }
3481
3482 if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
3483 $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
3484 return true;
3485 }
3486 return false;
3487 }
3488
3489 // a # color
3490 protected function color(&$out)
3491 {
3492 $m = array();
3493
3494 if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
3495 if (strlen($m[1]) > 7) {
3496 $out = array("string", "", array($m[1]));
3497 } else {
3498 $out = array("raw_color", $m[1]);
3499 }
3500 return true;
3501 }
3502
3503 return false;
3504 }
3505
3506 // consume an argument definition list surrounded by ()
3507 // each argument is a variable name with optional value
3508 // or at the end a ... or a variable named followed by ...
3509 // arguments are separated by , unless a ; is in the list, then ; is the
3510 // delimiter.
3511 protected function argumentDef(&$args, &$isVararg)
3512 {
3513 $value = array();
3514 $rhs = null;
3515
3516 $s = $this->seek();
3517 if (!$this->literal('(')) {
3518 return false;
3519 }
3520
3521 $values = array();
3522 $delim = ",";
3523 $method = "expressionList";
3524
3525 $isVararg = false;
3526 while (true) {
3527 if ($this->literal("...")) {
3528 $isVararg = true;
3529 break;
3530 }
3531
3532 if ($this->$method($value)) {
3533 if ($value[0] == "variable") {
3534 $arg = array("arg", $value[1]);
3535 $ss = $this->seek();
3536
3537 if ($this->assign() && $this->$method($rhs)) {
3538 $arg[] = $rhs;
3539 } else {
3540 $this->seek($ss);
3541 if ($this->literal("...")) {
3542 $arg[0] = "rest";
3543 $isVararg = true;
3544 }
3545 }
3546
3547 $values[] = $arg;
3548 if ($isVararg) {
3549 break;
3550 }
3551 continue;
3552 } else {
3553 $values[] = array("lit", $value);
3554 }
3555 }
3556
3557
3558 if (!$this->literal($delim)) {
3559 if ($delim == "," && $this->literal(";")) {
3560 // found new delim, convert existing args
3561 $delim = ";";
3562 $method = "propertyValue";
3563
3564 // transform arg list
3565 if (isset($values[1])) { // 2 items
3566 $newList = array();
3567 foreach ($values as $i => $arg) {
3568 switch ($arg[0]) {
3569 case "arg":
3570 if ($i) {
3571 $this->throwError("Cannot mix ; and , as delimiter types");
3572 }
3573 $newList[] = $arg[2];
3574 break;
3575 case "lit":
3576 $newList[] = $arg[1];
3577 break;
3578 case "rest":
3579 $this->throwError("Unexpected rest before semicolon");
3580 }
3581 }
3582
3583 $newList = array("list", ", ", $newList);
3584
3585 switch ($values[0][0]) {
3586 case "arg":
3587 $newArg = array("arg", $values[0][1], $newList);
3588 break;
3589 case "lit":
3590 $newArg = array("lit", $newList);
3591 break;
3592 }
3593
3594 } elseif ($values) { // 1 item
3595 $newArg = $values[0];
3596 }
3597
3598 if ($newArg) {
3599 $values = array($newArg);
3600 }
3601 } else {
3602 break;
3603 }
3604 }
3605 }
3606
3607 if (!$this->literal(')')) {
3608 $this->seek($s);
3609 return false;
3610 }
3611
3612 $args = $values;
3613
3614 return true;
3615 }
3616
3617 // consume a list of tags
3618 // this accepts a hanging delimiter
3619 protected function tags(&$tags, $simple = false, $delim = ',')
3620 {
3621 $tt = array();
3622
3623 $tags = array();
3624 while ($this->tag($tt, $simple)) {
3625 $tags[] = $tt;
3626 if (!$this->literal($delim)) {
3627 break;
3628 }
3629 }
3630 if (count($tags) == 0) {
3631 return false;
3632 }
3633
3634 return true;
3635 }
3636
3637 // list of tags of specifying mixin path
3638 // optionally separated by > (lazy, accepts extra >)
3639 protected function mixinTags(&$tags)
3640 {
3641 $tt = array();
3642
3643 $tags = array();
3644 while ($this->tag($tt, true)) {
3645 $tags[] = $tt;
3646 $this->literal(">");
3647 }
3648
3649 if (!$tags) {
3650 return false;
3651 }
3652
3653 return true;
3654 }
3655
3656 // a bracketed value (contained within in a tag definition)
3657 protected function tagBracket(&$parts, &$hasExpression)
3658 {
3659 $str = null;
3660 $inter = null;
3661 $word = null;
3662
3663 // speed shortcut
3664 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
3665 return false;
3666 }
3667
3668 $s = $this->seek();
3669
3670 $hasInterpolation = false;
3671
3672 if ($this->literal("[", false)) {
3673 $attrParts = array("[");
3674 // keyword, string, operator
3675 while (true) {
3676 if ($this->literal("]", false)) {
3677 $this->count--;
3678 break; // get out early
3679 }
3680
3681 $m = array();
3682 if ($this->match('\s+', $m)) {
3683 $attrParts[] = " ";
3684 continue;
3685 }
3686 if ($this->string($str)) {
3687 // escape parent selector, (yuck)
3688 foreach ($str[2] as &$chunk) {
3689 $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
3690 }
3691
3692 $attrParts[] = $str;
3693 $hasInterpolation = true;
3694 continue;
3695 }
3696
3697 if ($this->keyword($word)) {
3698 $attrParts[] = $word;
3699 continue;
3700 }
3701
3702 if ($this->interpolation($inter)) {
3703 $attrParts[] = $inter;
3704 $hasInterpolation = true;
3705 continue;
3706 }
3707
3708 // operator, handles attr namespace too
3709 if ($this->match('[|-~\$\*\^=]+', $m)) {
3710 $attrParts[] = $m[0];
3711 continue;
3712 }
3713
3714 break;
3715 }
3716
3717 if ($this->literal("]", false)) {
3718 $attrParts[] = "]";
3719 foreach ($attrParts as $part) {
3720 $parts[] = $part;
3721 }
3722 $hasExpression = $hasExpression || $hasInterpolation;
3723 return true;
3724 }
3725 $this->seek($s);
3726 }
3727
3728 $this->seek($s);
3729 return false;
3730 }
3731
3732 // a space separated list of selectors
3733 protected function tag(&$tag, $simple = false)
3734 {
3735 $interp = null;
3736 $unit = null;
3737
3738 if ($simple) {
3739 $chars = '^@,:;{}\][>\‍(\‍) "\'';
3740 } else {
3741 $chars = '^@,;{}["\'';
3742 }
3743 $s = $this->seek();
3744
3745 $hasExpression = false;
3746 $parts = array();
3747 while ($this->tagBracket($parts, $hasExpression));
3748
3749 $oldWhite = $this->eatWhiteDefault;
3750 $this->eatWhiteDefault = false;
3751
3752 while (true) {
3753 $m = array();
3754 if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
3755 $parts[] = $m[1];
3756 if ($simple) {
3757 break;
3758 }
3759
3760 while ($this->tagBracket($parts, $hasExpression));
3761 continue;
3762 }
3763
3764 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
3765 if ($this->interpolation($interp)) {
3766 $hasExpression = true;
3767 $interp[2] = true; // don't unescape
3768 $parts[] = $interp;
3769 continue;
3770 }
3771
3772 if ($this->literal("@")) {
3773 $parts[] = "@";
3774 continue;
3775 }
3776 }
3777
3778 if ($this->unit($unit)) { // for keyframes
3779 $parts[] = $unit[1];
3780 $parts[] = $unit[2];
3781 continue;
3782 }
3783
3784 break;
3785 }
3786
3787 $this->eatWhiteDefault = $oldWhite;
3788 if (!$parts) {
3789 $this->seek($s);
3790 return false;
3791 }
3792
3793 if ($hasExpression) {
3794 $tag = array("exp", array("string", "", $parts));
3795 } else {
3796 $tag = trim(implode($parts));
3797 }
3798
3799 $this->whitespace();
3800 return true;
3801 }
3802
3803 // a css function
3804 protected function func(&$func)
3805 {
3806 $s = $this->seek();
3807
3808 $m = array();
3809 $value = array();
3810 $string = array();
3811 $name = null;
3812
3813 if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
3814 $fname = $m[1];
3815
3816 $sPreArgs = $this->seek();
3817
3818 $args = array();
3819 while (true) {
3820 $ss = $this->seek();
3821 // this ugly nonsense is for ie filter properties
3822 if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
3823 $args[] = array("string", "", array($name, "=", $value));
3824 } else {
3825 $this->seek($ss);
3826 if ($this->expressionList($value)) {
3827 $args[] = $value;
3828 }
3829 }
3830
3831 if (!$this->literal(',')) {
3832 break;
3833 }
3834 }
3835 $args = array('list', ',', $args);
3836
3837 if ($this->literal(')')) {
3838 $func = array('function', $fname, $args);
3839 return true;
3840 } elseif ($fname == 'url') {
3841 // couldn't parse and in url? treat as string
3842 $this->seek($sPreArgs);
3843 if ($this->openString(")", $string) && $this->literal(")")) {
3844 $func = array('function', $fname, $string);
3845 return true;
3846 }
3847 }
3848 }
3849
3850 $this->seek($s);
3851 return false;
3852 }
3853
3854 // consume a less variable
3855 protected function variable(&$name)
3856 {
3857 $sub = null;
3858 $name = null;
3859
3860 $s = $this->seek();
3861 if ($this->literal($this->lessc->vPrefix, false) &&
3862 ($this->variable($sub) || $this->keyword($name))
3863 ) {
3864 if (!empty($sub)) {
3865 $name = array('variable', $sub);
3866 } else {
3867 $name = $this->lessc->vPrefix.$name;
3868 }
3869 return true;
3870 }
3871
3872 $name = null;
3873 $this->seek($s);
3874 return false;
3875 }
3876
3881 protected function assign($name = null)
3882 {
3883 if ($name) {
3884 $this->currentProperty = $name;
3885 }
3886 return $this->literal(':') || $this->literal('=');
3887 }
3888
3889 // consume a keyword
3890 protected function keyword(&$word)
3891 {
3892 $m = array();
3893 if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
3894 $word = $m[1];
3895 return true;
3896 }
3897 return false;
3898 }
3899
3900 // consume an end of statement delimiter
3901 protected function end()
3902 {
3903 if ($this->literal(';', false)) {
3904 return true;
3905 } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
3906 // if there is end of file or a closing block next then we don't need a ;
3907 return true;
3908 }
3909 return false;
3910 }
3911
3912 protected function guards(&$guards)
3913 {
3914 $g = null;
3915
3916 $s = $this->seek();
3917
3918 if (!$this->literal("when")) {
3919 $this->seek($s);
3920 return false;
3921 }
3922
3923 $guards = array();
3924
3925 while ($this->guardGroup($g)) {
3926 $guards[] = $g;
3927 if (!$this->literal(",")) {
3928 break;
3929 }
3930 }
3931
3932 if (count($guards) == 0) {
3933 $guards = null;
3934 $this->seek($s);
3935 return false;
3936 }
3937
3938 return true;
3939 }
3940
3941 // a bunch of guards that are and'd together
3942 // TODO rename to guardGroup
3943 protected function guardGroup(&$guardGroup)
3944 {
3945 $guard = null;
3946
3947 $s = $this->seek();
3948 $guardGroup = array();
3949 while ($this->guard($guard)) {
3950 $guardGroup[] = $guard;
3951 if (!$this->literal("and")) {
3952 break;
3953 }
3954 }
3955
3956 if (count($guardGroup) == 0) {
3957 $guardGroup = null;
3958 $this->seek($s);
3959 return false;
3960 }
3961
3962 return true;
3963 }
3964
3965 protected function guard(&$guard)
3966 {
3967 $exp = null;
3968
3969 $s = $this->seek();
3970 $negate = $this->literal("not");
3971
3972 if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
3973 $guard = $exp;
3974 if ($negate) {
3975 $guard = array("negate", $guard);
3976 }
3977 return true;
3978 }
3979
3980 $this->seek($s);
3981 return false;
3982 }
3983
3984 /* raw parsing functions */
3985
3986 protected function literal($what, $eatWhitespace = null)
3987 {
3988 if ($eatWhitespace === null) {
3989 $eatWhitespace = $this->eatWhiteDefault;
3990 }
3991
3992 // shortcut on single letter
3993 if (!isset($what[1]) && isset($this->buffer[$this->count])) {
3994 if ($this->buffer[$this->count] == $what) {
3995 if (!$eatWhitespace) {
3996 $this->count++;
3997 return true;
3998 }
3999 // goes below...
4000 } else {
4001 return false;
4002 }
4003 }
4004
4005 if (!isset(self::$literalCache[$what])) {
4006 self::$literalCache[$what] = Lessc::preg_quote($what);
4007 }
4008
4009 $m = array();
4010 return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
4011 }
4012
4013 protected function genericList(&$out, $parseItem, $delim = "", $flatten = true)
4014 {
4015 $value = null;
4016
4017 $s = $this->seek();
4018 $items = array();
4019 while ($this->$parseItem($value)) {
4020 $items[] = $value;
4021 if ($delim) {
4022 if (!$this->literal($delim)) {
4023 break;
4024 }
4025 }
4026 }
4027
4028 if (count($items) == 0) {
4029 $this->seek($s);
4030 return false;
4031 }
4032
4033 if ($flatten && count($items) == 1) {
4034 $out = $items[0];
4035 } else {
4036 $out = array("list", $delim, $items);
4037 }
4038
4039 return true;
4040 }
4041
4042
4043 // advance counter to next occurrence of $what
4044 // $until - don't include $what in advance
4045 // $allowNewline, if string, will be used as valid char set
4046 protected function to($what, &$out, $until = false, $allowNewline = false)
4047 {
4048 if (is_string($allowNewline)) {
4049 $validChars = $allowNewline;
4050 } else {
4051 $validChars = $allowNewline ? "." : "[^\n]";
4052 }
4053 $m = array();
4054 if (!$this->match('('.$validChars.'*?)'.Lessc::preg_quote($what), $m, !$until)) {
4055 return false;
4056 }
4057 if ($until) {
4058 $this->count -= strlen($what); // give back $what
4059 }
4060 $out = $m[1];
4061 return true;
4062 }
4063
4064 // try to match something on head of buffer
4065 protected function match($regex, &$out, $eatWhitespace = null)
4066 {
4067 if ($eatWhitespace === null) {
4068 $eatWhitespace = $this->eatWhiteDefault;
4069 }
4070
4071 $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
4072 if (preg_match($r, $this->buffer, $out, 0, $this->count)) {
4073 $this->count += strlen($out[0]);
4074 if ($eatWhitespace && $this->writeComments) {
4075 $this->whitespace();
4076 }
4077 return true;
4078 }
4079 return false;
4080 }
4081
4082 // match some whitespace
4083 protected function whitespace()
4084 {
4085 if ($this->writeComments) {
4086 $gotWhite = false;
4087 $m = array();
4088 while (preg_match(self::$whitePattern, $this->buffer, $m, 0, $this->count)) {
4089 if (isset($m[1]) && empty($this->seenComments[$this->count])) {
4090 $this->append(array("comment", $m[1]));
4091 $this->seenComments[$this->count] = true;
4092 }
4093 $this->count += strlen($m[0]);
4094 $gotWhite = true;
4095 }
4096 return $gotWhite;
4097 } else {
4098 $this->match("", $m);
4099 return strlen($m[0]) > 0;
4100 }
4101 }
4102
4103 // match something without consuming it
4104 protected function peek($regex, &$out = null, $from = null)
4105 {
4106 if (is_null($from)) {
4107 $from = $this->count;
4108 }
4109 $r = '/'.$regex.'/Ais';
4110 $result = preg_match($r, $this->buffer, $out, 0, $from);
4111
4112 return $result;
4113 }
4114
4115 // seek to a spot in the buffer or return where we are on no argument
4116 protected function seek($where = null)
4117 {
4118 if ($where === null) {
4119 return $this->count;
4120 } else {
4121 $this->count = $where;
4122 }
4123 return true;
4124 }
4125
4126 /* misc functions */
4127
4128 public function throwError($msg = "parse error", $count = null)
4129 {
4130 $count = is_null($count) ? $this->count : $count;
4131
4132 $line = $this->line +
4133 substr_count(substr($this->buffer, 0, $count), "\n");
4134
4135 if (!empty($this->sourceName)) {
4136 $loc = "$this->sourceName on line $line";
4137 } else {
4138 $loc = "line: $line";
4139 }
4140
4141 // TODO this depends on $this->count
4142 $m = array();
4143 if ($this->peek("(.*?)(\n|$)", $m, $count)) {
4144 throw new exception("$msg: failed at `$m[1]` $loc");
4145 } else {
4146 throw new exception("$msg: $loc");
4147 }
4148 }
4149
4150 protected function pushBlock($selectors = null, $type = null)
4151 {
4152 $b = new stdclass();
4153 $b->parent = $this->env;
4154
4155 $b->type = $type;
4156 $b->id = self::$nextBlockId++;
4157
4158 $b->isVararg = false; // TODO: kill me from here
4159 $b->tags = $selectors;
4160
4161 $b->props = array();
4162 $b->children = array();
4163
4164 $this->env = $b;
4165 return $b;
4166 }
4167
4168 // push a block that doesn't multiply tags
4169 protected function pushSpecialBlock($type)
4170 {
4171 return $this->pushBlock(null, $type);
4172 }
4173
4174 // append a property to the current block
4175 protected function append($prop, $pos = null)
4176 {
4177 if ($pos !== null) {
4178 $prop[-1] = $pos;
4179 }
4180 $this->env->props[] = $prop;
4181 }
4182
4183 // pop something off the stack
4184 protected function pop()
4185 {
4186 $old = $this->env;
4187 $this->env = $this->env->parent;
4188 return $old;
4189 }
4190
4191 // remove comments from $text
4192 // todo: make it work for all functions, not just url
4193 protected function removeComments($text)
4194 {
4195 $look = array(
4196 'url(', '//', '/*', '"', "'"
4197 );
4198
4199 $out = '';
4200 $min = null;
4201 while (true) {
4202 // find the next item
4203 foreach ($look as $token) {
4204 $pos = strpos($text, $token);
4205 if ($pos !== false) {
4206 if (!isset($min) || $pos < $min[1]) {
4207 $min = array($token, $pos);
4208 }
4209 }
4210 }
4211
4212 if (is_null($min)) {
4213 break;
4214 }
4215
4216 $count = $min[1];
4217 $skip = 0;
4218 $newlines = 0;
4219 switch ($min[0]) {
4220 case 'url(':
4221 $m = array();
4222 if (preg_match('/url\‍(.*?\‍)/', $text, $m, 0, $count)) {
4223 $count += strlen($m[0]) - strlen($min[0]);
4224 }
4225 break;
4226 case '"':
4227 case "'":
4228 $m = array();
4229 if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count)) {
4230 $count += strlen($m[0]) - 1;
4231 }
4232 break;
4233 case '//':
4234 $skip = strpos($text, "\n", $count);
4235 if ($skip === false) {
4236 $skip = strlen($text) - $count;
4237 } else {
4238 $skip -= $count;
4239 }
4240 break;
4241 case '/*':
4242 $m = array();
4243 if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
4244 $skip = strlen($m[0]);
4245 $newlines = substr_count($m[0], "\n");
4246 }
4247 break;
4248 }
4249
4250 if ($skip == 0) {
4251 $count += strlen($min[0]);
4252 }
4253
4254 $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
4255 $text = substr($text, $count + $skip);
4256
4257 $min = null;
4258 }
4259
4260 return $out.$text;
4261 }
4262}
4263
4265{
4266 public $indentChar = " ";
4267
4268 public $break = "\n";
4269 public $open = " {";
4270 public $close = "}";
4271 public $selectorSeparator = ", ";
4272 public $assignSeparator = ":";
4273
4274 public $openSingle = " { ";
4275 public $closeSingle = " }";
4276
4277 public $disableSingle = false;
4278 public $breakSelectors = false;
4279
4280 public $compressColors = false;
4281 public $indentLevel;
4282
4283 public function __construct()
4284 {
4285 $this->indentLevel = 0;
4286 }
4287
4288 public function indentStr($n = 0)
4289 {
4290 return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
4291 }
4292
4293 public function property($name, $value)
4294 {
4295 return $name.$this->assignSeparator.$value.";";
4296 }
4297
4298 protected function isEmpty($block)
4299 {
4300 if (empty($block->lines)) {
4301 foreach ($block->children as $child) {
4302 if (!$this->isEmpty($child)) {
4303 return false;
4304 }
4305 }
4306
4307 return true;
4308 }
4309 return false;
4310 }
4311
4312 public function block($block)
4313 {
4314 if ($this->isEmpty($block)) {
4315 return;
4316 }
4317
4318 $inner = $pre = $this->indentStr();
4319
4320 $isSingle = !$this->disableSingle &&
4321 is_null($block->type) && count($block->lines) == 1;
4322
4323 if (!empty($block->selectors)) {
4324 $this->indentLevel++;
4325
4326 if ($this->breakSelectors) {
4327 $selectorSeparator = $this->selectorSeparator.$this->break.$pre;
4328 } else {
4329 $selectorSeparator = $this->selectorSeparator;
4330 }
4331
4332 echo $pre.
4333 implode($selectorSeparator, $block->selectors);
4334 if ($isSingle) {
4335 echo $this->openSingle;
4336 $inner = "";
4337 } else {
4338 echo $this->open.$this->break;
4339 $inner = $this->indentStr();
4340 }
4341 }
4342
4343 if (!empty($block->lines)) {
4344 $glue = $this->break.$inner;
4345 echo $inner.implode($glue, $block->lines);
4346 if (!$isSingle && !empty($block->children)) {
4347 echo $this->break;
4348 }
4349 }
4350
4351 foreach ($block->children as $child) {
4352 $this->block($child);
4353 }
4354
4355 if (!empty($block->selectors)) {
4356 if (!$isSingle && empty($block->children)) {
4357 echo $this->break;
4358 }
4359
4360 if ($isSingle) {
4361 echo $this->closeSingle.$this->break;
4362 } else {
4363 echo $pre.$this->close.$this->break;
4364 }
4365
4366 $this->indentLevel--;
4367 }
4368 }
4369}
4370
4375{
4376 public $disableSingle = true;
4377 public $open = "{";
4378 public $selectorSeparator = ",";
4379 public $assignSeparator = ":";
4380 public $break = "";
4381 public $compressColors = true;
4382
4383 public function indentStr($n = 0)
4384 {
4385 return "";
4386 }
4387}
4388
4393{
4394 public $disableSingle = true;
4395 public $breakSelectors = true;
4396 public $assignSeparator = ": ";
4397 public $selectorSeparator = ",";
4398}
$id
Definition account.php:39
lessphp v0.8.0 http://leafo.net/lessphp
compileBlock($block)
Recursively compiles a block.
lib_mix($args)
lib_mix mixes two colors by weight mix(@color1, @color2, [@weight: 50%]); http://sass-lang....
__construct($fname=null)
Initialize any static state, can initialize parser for a file $opts isn't used yet.
cachedCompile($in, $force=false)
Execute lessphp on a .less file or a lessphp cache structure.
lib_data_uri($value)
Given an url, decide whether to output a regular link or the base64-encoded contents of the file.
funcToColor($func)
Convert the rgb, rgba, hsl color literals of function type as returned by the parser into values of c...
deduplicate($lines)
Deduplicate lines in a block.
lib_shade($args)
Mix color with black in variable proportion.
fileExists($name)
fileExists
toRGB($color)
Converts a hsl array into a color value in rgb.
lib_contrast($args)
lib_contrast
throwError($msg=null)
Uses the current value of $this->count to show line and line number.
colorArgs($args)
Helper function to get arguments for color manipulation functions.
compileValue($value)
Compiles a primitive value into a CSS property value.
lib_tint($args)
Mix color with white in variable proportion.
Class for compressed result.
Class for lessjs.
expHelper($lhs, $minP)
recursively parse infix equation with $lhs at precedence $minP
parseChunk()
Parse a single chunk off the head of the buffer and append it to the current parse environment.
assign($name=null)
Consume an assignment operator Can optionally take a name that will be set to the current property na...
parse($buffer)
Parse a string.
$inParens
if we are in parens we can be more liberal with whitespace around operators because it must evaluate ...
expression(&$out)
Attempt to consume an expression.