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