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