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