dolibarr  16.0.5
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  $this->throwError("Failed to assign arg ".$a[1]);
707  $value = null; // :(
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  }
1015 
1016  protected function lib_isnumber($value)
1017  {
1018  return $this->toBool($value[0] == "number");
1019  }
1020 
1021  protected function lib_isstring($value)
1022  {
1023  return $this->toBool($value[0] == "string");
1024  }
1025 
1026  protected function lib_iscolor($value)
1027  {
1028  return $this->toBool($this->coerceColor($value));
1029  }
1030 
1031  protected function lib_iskeyword($value)
1032  {
1033  return $this->toBool($value[0] == "keyword");
1034  }
1035 
1036  protected function lib_ispixel($value)
1037  {
1038  return $this->toBool($value[0] == "number" && $value[2] == "px");
1039  }
1040 
1041  protected function lib_ispercentage($value)
1042  {
1043  return $this->toBool($value[0] == "number" && $value[2] == "%");
1044  }
1045 
1046  protected function lib_isem($value)
1047  {
1048  return $this->toBool($value[0] == "number" && $value[2] == "em");
1049  }
1050 
1051  protected function lib_isrem($value)
1052  {
1053  return $this->toBool($value[0] == "number" && $value[2] == "rem");
1054  }
1055 
1056  protected function lib_rgbahex($color)
1057  {
1058  $color = $this->coerceColor($color);
1059  if (is_null($color)) {
1060  $this->throwError("color expected for rgbahex");
1061  }
1062 
1063  return sprintf(
1064  "#%02x%02x%02x%02x",
1065  isset($color[4]) ? $color[4] * 255 : 255,
1066  $color[1],
1067  $color[2],
1068  $color[3]
1069  );
1070  }
1071 
1072  protected function lib_argb($color)
1073  {
1074  return $this->lib_rgbahex($color);
1075  }
1076 
1083  protected function lib_data_uri($value)
1084  {
1085  $mime = ($value[0] === 'list') ? $value[2][0][2] : null;
1086  $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0];
1087 
1088  $fullpath = $this->findImport($url);
1089 
1090  if ($fullpath && ($fsize = filesize($fullpath)) !== false) {
1091  // IE8 can't handle data uris larger than 32KB
1092  if ($fsize / 1024 < 32) {
1093  if (is_null($mime)) {
1094  if (class_exists('finfo')) { // php 5.3+
1095  $finfo = new finfo(FILEINFO_MIME);
1096  $mime = explode('; ', $finfo->file($fullpath));
1097  $mime = $mime[0];
1098  } elseif (function_exists('mime_content_type')) { // PHP 5.2
1099  $mime = mime_content_type($fullpath);
1100  }
1101  }
1102 
1103  if (!is_null($mime)) { // fallback if the mime type is still unknown
1104  $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
1105  }
1106  }
1107  }
1108 
1109  return 'url("'.$url.'")';
1110  }
1111 
1112  // utility func to unquote a string
1113  protected function lib_e($arg)
1114  {
1115  switch ($arg[0]) {
1116  case "list":
1117  $items = $arg[2];
1118  if (isset($items[0])) {
1119  return $this->lib_e($items[0]);
1120  }
1121  $this->throwError("unrecognised input");
1122  return null;
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  }
1310 
1311  // set the alpha of the color
1312  protected function lib_fade($args)
1313  {
1314  list($color, $alpha) = $this->colorArgs($args);
1315  $color[4] = $this->clamp($alpha / 100.0);
1316  return $color;
1317  }
1318 
1319  protected function lib_percentage($arg)
1320  {
1321  $num = $this->assertNumber($arg);
1322  return array("number", $num * 100, "%");
1323  }
1324 
1336  protected function lib_tint($args)
1337  {
1338  $white = ['color', 255, 255, 255];
1339  if ($args[0] == 'color') {
1340  return $this->lib_mix(['list', ',', [$white, $args]]);
1341  } elseif ($args[0] == "list" && count($args[2]) == 2) {
1342  return $this->lib_mix([$args[0], $args[1], [$white, $args[2][0], $args[2][1]]]);
1343  } else {
1344  $this->throwError("tint expects (color, weight)");
1345  }
1346  }
1347 
1359  protected function lib_shade($args)
1360  {
1361  $black = ['color', 0, 0, 0];
1362  if ($args[0] == 'color') {
1363  return $this->lib_mix(['list', ',', [$black, $args]]);
1364  } elseif ($args[0] == "list" && count($args[2]) == 2) {
1365  return $this->lib_mix([$args[0], $args[1], [$black, $args[2][0], $args[2][1]]]);
1366  } else {
1367  $this->throwError("shade expects (color, weight)");
1368  }
1369  }
1370 
1371  // mixes two colors by weight
1372  // mix(@color1, @color2, [@weight: 50%]);
1373  // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
1374  protected function lib_mix($args)
1375  {
1376  if ($args[0] != "list" || count($args[2]) < 2) {
1377  $this->throwError("mix expects (color1, color2, weight)");
1378  }
1379 
1380  list($first, $second) = $args[2];
1381  $first = $this->assertColor($first);
1382  $second = $this->assertColor($second);
1383 
1384  $first_a = $this->lib_alpha($first);
1385  $second_a = $this->lib_alpha($second);
1386 
1387  if (isset($args[2][2])) {
1388  $weight = $args[2][2][1] / 100.0;
1389  } else {
1390  $weight = 0.5;
1391  }
1392 
1393  $w = $weight * 2 - 1;
1394  $a = $first_a - $second_a;
1395 
1396  $w1 = (($w * $a == -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
1397  $w2 = 1.0 - $w1;
1398 
1399  $new = array('color',
1400  $w1 * $first[1] + $w2 * $second[1],
1401  $w1 * $first[2] + $w2 * $second[2],
1402  $w1 * $first[3] + $w2 * $second[3],
1403  );
1404 
1405  if ($first_a != 1.0 || $second_a != 1.0) {
1406  $new[] = $first_a * $weight + $second_a * ($weight - 1);
1407  }
1408 
1409  return $this->fixColor($new);
1410  }
1411 
1412  protected function lib_contrast($args)
1413  {
1414  $darkColor = array('color', 0, 0, 0);
1415  $lightColor = array('color', 255, 255, 255);
1416  $threshold = 0.43;
1417 
1418  if ($args[0] == 'list') {
1419  $inputColor = (isset($args[2][0])) ? $this->assertColor($args[2][0]) : $lightColor;
1420  $darkColor = (isset($args[2][1])) ? $this->assertColor($args[2][1]) : $darkColor;
1421  $lightColor = (isset($args[2][2])) ? $this->assertColor($args[2][2]) : $lightColor;
1422  $threshold = (isset($args[2][3])) ? $this->assertNumber($args[2][3]) : $threshold;
1423  } else {
1424  $inputColor = $this->assertColor($args);
1425  }
1426 
1427  $inputColor = $this->coerceColor($inputColor);
1428  $darkColor = $this->coerceColor($darkColor);
1429  $lightColor = $this->coerceColor($lightColor);
1430 
1431  //Figure out which is actually light and dark!
1432  if ($this->toLuma($darkColor) > $this->toLuma($lightColor)) {
1433  $t = $lightColor;
1434  $lightColor = $darkColor;
1435  $darkColor = $t;
1436  }
1437 
1438  $inputColor_alpha = $this->lib_alpha($inputColor);
1439  if (($this->toLuma($inputColor) * $inputColor_alpha) < $threshold) {
1440  return $lightColor;
1441  }
1442  return $darkColor;
1443  }
1444 
1445  private function toLuma($color)
1446  {
1447  list(, $r, $g, $b) = $this->coerceColor($color);
1448 
1449  $r = $r / 255;
1450  $g = $g / 255;
1451  $b = $b / 255;
1452 
1453  $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
1454  $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
1455  $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
1456 
1457  return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
1458  }
1459 
1460  protected function lib_luma($color)
1461  {
1462  return array("number", round($this->toLuma($color) * 100, 8), "%");
1463  }
1464 
1465 
1466  public function assertColor($value, $error = "expected color value")
1467  {
1468  $color = $this->coerceColor($value);
1469  if (is_null($color)) {
1470  $this->throwError($error);
1471  }
1472  return $color;
1473  }
1474 
1475  public function assertNumber($value, $error = "expecting number")
1476  {
1477  if ($value[0] == "number") {
1478  return $value[1];
1479  }
1480  $this->throwError($error);
1481  }
1482 
1483  public function assertArgs($value, $expectedArgs, $name = "")
1484  {
1485  if ($expectedArgs == 1) {
1486  return $value;
1487  } else {
1488  if ($value[0] !== "list" || $value[1] != ",") {
1489  $this->throwError("expecting list");
1490  }
1491  $values = $value[2];
1492  $numValues = count($values);
1493  if ($expectedArgs != $numValues) {
1494  if ($name) {
1495  $name = $name.": ";
1496  }
1497 
1498  $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
1499  }
1500 
1501  return $values;
1502  }
1503  }
1504 
1505  protected function toHSL($color)
1506  {
1507  if ($color[0] === 'hsl') {
1508  return $color;
1509  }
1510 
1511  $r = $color[1] / 255;
1512  $g = $color[2] / 255;
1513  $b = $color[3] / 255;
1514 
1515  $min = min($r, $g, $b);
1516  $max = max($r, $g, $b);
1517 
1518  $L = ($min + $max) / 2;
1519  if ($min == $max) {
1520  $S = $H = 0;
1521  } else {
1522  if ($L < 0.5) {
1523  $S = ($max - $min) / ($max + $min);
1524  } else {
1525  $S = ($max - $min) / (2.0 - $max - $min);
1526  }
1527  if ($r == $max) {
1528  $H = ($g - $b) / ($max - $min);
1529  } elseif ($g == $max) {
1530  $H = 2.0 + ($b - $r) / ($max - $min);
1531  } elseif ($b == $max) {
1532  $H = 4.0 + ($r - $g) / ($max - $min);
1533  }
1534  }
1535 
1536  $out = array('hsl',
1537  ($H < 0 ? $H + 6 : $H) * 60,
1538  $S * 100,
1539  $L * 100,
1540  );
1541 
1542  if (count($color) > 4) {
1543  // copy alpha
1544  $out[] = $color[4];
1545  }
1546  return $out;
1547  }
1548 
1549  protected function toRGB_helper($comp, $temp1, $temp2)
1550  {
1551  if ($comp < 0) {
1552  $comp += 1.0;
1553  } elseif ($comp > 1) {
1554  $comp -= 1.0;
1555  }
1556 
1557  if (6 * $comp < 1) {
1558  return $temp1 + ($temp2 - $temp1) * 6 * $comp;
1559  }
1560  if (2 * $comp < 1) {
1561  return $temp2;
1562  }
1563  if (3 * $comp < 2) {
1564  return $temp1 + ($temp2 - $temp1) * ((2 / 3) - $comp) * 6;
1565  }
1566 
1567  return $temp1;
1568  }
1569 
1574  protected function toRGB($color)
1575  {
1576  if ($color[0] === 'color') {
1577  return $color;
1578  }
1579 
1580  $H = $color[1] / 360;
1581  $S = $color[2] / 100;
1582  $L = $color[3] / 100;
1583 
1584  if ($S == 0) {
1585  $r = $g = $b = $L;
1586  } else {
1587  $temp2 = $L < 0.5 ?
1588  $L * (1.0 + $S) : $L + $S - $L * $S;
1589 
1590  $temp1 = 2.0 * $L - $temp2;
1591 
1592  $r = $this->toRGB_helper($H + 1 / 3, $temp1, $temp2);
1593  $g = $this->toRGB_helper($H, $temp1, $temp2);
1594  $b = $this->toRGB_helper($H - 1 / 3, $temp1, $temp2);
1595  }
1596 
1597  // $out = array('color', round($r*255), round($g*255), round($b*255));
1598  $out = array('color', $r * 255, $g * 255, $b * 255);
1599  if (count($color) > 4) {
1600  // copy alpha
1601  $out[] = $color[4];
1602  }
1603  return $out;
1604  }
1605 
1606  protected function clamp($v, $max = 1, $min = 0)
1607  {
1608  return min($max, max($min, $v));
1609  }
1610 
1615  protected function funcToColor($func)
1616  {
1617  $fname = $func[1];
1618  if ($func[2][0] != 'list') {
1619  // need a list of arguments
1620  return false;
1621  }
1622  $rawComponents = $func[2][2];
1623 
1624  if ($fname == 'hsl' || $fname == 'hsla') {
1625  $hsl = array('hsl');
1626  $i = 0;
1627  foreach ($rawComponents as $c) {
1628  $val = $this->reduce($c);
1629  $val = isset($val[1]) ? floatval($val[1]) : 0;
1630 
1631  if ($i == 0) {
1632  $clamp = 360;
1633  } elseif ($i < 3) {
1634  $clamp = 100;
1635  } else {
1636  $clamp = 1;
1637  }
1638 
1639  $hsl[] = $this->clamp($val, $clamp);
1640  $i++;
1641  }
1642 
1643  while (count($hsl) < 4) {
1644  $hsl[] = 0;
1645  }
1646  return $this->toRGB($hsl);
1647  } elseif ($fname == 'rgb' || $fname == 'rgba') {
1648  $components = array();
1649  $i = 1;
1650  foreach ($rawComponents as $c) {
1651  $c = $this->reduce($c);
1652  if ($i < 4) {
1653  if ($c[0] == "number" && $c[2] == "%") {
1654  $components[] = 255 * ($c[1] / 100);
1655  } else {
1656  $components[] = floatval($c[1]);
1657  }
1658  } elseif ($i == 4) {
1659  if ($c[0] == "number" && $c[2] == "%") {
1660  $components[] = 1.0 * ($c[1] / 100);
1661  } else {
1662  $components[] = floatval($c[1]);
1663  }
1664  } else {
1665  break;
1666  }
1667 
1668  $i++;
1669  }
1670  while (count($components) < 3) {
1671  $components[] = 0;
1672  }
1673  array_unshift($components, 'color');
1674  return $this->fixColor($components);
1675  }
1676 
1677  return false;
1678  }
1679 
1680  protected function reduce($value, $forExpression = false)
1681  {
1682  switch ($value[0]) {
1683  case "interpolate":
1684  $reduced = $this->reduce($value[1]);
1685  $var = $this->compileValue($reduced);
1686  $res = $this->reduce(array("variable", $this->vPrefix.$var));
1687 
1688  if ($res[0] == "raw_color") {
1689  $res = $this->coerceColor($res);
1690  }
1691 
1692  if (empty($value[2])) {
1693  $res = $this->lib_e($res);
1694  }
1695 
1696  return $res;
1697  case "variable":
1698  $key = $value[1];
1699  if (is_array($key)) {
1700  $key = $this->reduce($key);
1701  $key = $this->vPrefix.$this->compileValue($this->lib_e($key));
1702  }
1703 
1704  $seen = & $this->env->seenNames;
1705 
1706  if (!empty($seen[$key])) {
1707  $this->throwError("infinite loop detected: $key");
1708  }
1709 
1710  $seen[$key] = true;
1711  $out = $this->reduce($this->get($key));
1712  $seen[$key] = false;
1713  return $out;
1714  case "list":
1715  foreach ($value[2] as &$item) {
1716  $item = $this->reduce($item, $forExpression);
1717  }
1718  return $value;
1719  case "expression":
1720  return $this->evaluate($value);
1721  case "string":
1722  foreach ($value[2] as &$part) {
1723  if (is_array($part)) {
1724  $strip = $part[0] == "variable";
1725  $part = $this->reduce($part);
1726  if ($strip) {
1727  $part = $this->lib_e($part);
1728  }
1729  }
1730  }
1731  return $value;
1732  case "escape":
1733  list(,$inner) = $value;
1734  return $this->lib_e($this->reduce($inner));
1735  case "function":
1736  $color = $this->funcToColor($value);
1737  if ($color) {
1738  return $color;
1739  }
1740 
1741  list(, $name, $args) = $value;
1742  if ($name == "%") {
1743  $name = "_sprintf";
1744  }
1745 
1746  $f = isset($this->libFunctions[$name]) ?
1747  $this->libFunctions[$name] : array($this, 'lib_'.str_replace('-', '_', $name));
1748 
1749  if (is_callable($f)) {
1750  if ($args[0] == 'list') {
1751  $args = self::compressList($args[2], $args[1]);
1752  }
1753 
1754  $ret = call_user_func($f, $this->reduce($args, true), $this);
1755 
1756  if (is_null($ret)) {
1757  return array("string", "", array(
1758  $name, "(", $args, ")"
1759  ));
1760  }
1761 
1762  // convert to a typed value if the result is a php primitive
1763  if (is_numeric($ret)) {
1764  $ret = array('number', $ret, "");
1765  } elseif (!is_array($ret)) {
1766  $ret = array('keyword', $ret);
1767  }
1768 
1769  return $ret;
1770  }
1771 
1772  // plain function, reduce args
1773  $value[2] = $this->reduce($value[2]);
1774  return $value;
1775  case "unary":
1776  list(, $op, $exp) = $value;
1777  $exp = $this->reduce($exp);
1778 
1779  if ($exp[0] == "number") {
1780  switch ($op) {
1781  case "+":
1782  return $exp;
1783  case "-":
1784  $exp[1] *= -1;
1785  return $exp;
1786  }
1787  }
1788  return array("string", "", array($op, $exp));
1789  }
1790 
1791  if ($forExpression) {
1792  switch ($value[0]) {
1793  case "keyword":
1794  if ($color = $this->coerceColor($value)) {
1795  return $color;
1796  }
1797  break;
1798  case "raw_color":
1799  return $this->coerceColor($value);
1800  }
1801  }
1802 
1803  return $value;
1804  }
1805 
1806 
1807  // coerce a value for use in color operation
1808  protected function coerceColor($value)
1809  {
1810  switch ($value[0]) {
1811  case 'color':
1812  return $value;
1813  case 'raw_color':
1814  $c = array("color", 0, 0, 0);
1815  $colorStr = substr($value[1], 1);
1816  $num = hexdec($colorStr);
1817  $width = strlen($colorStr) == 3 ? 16 : 256;
1818 
1819  for ($i = 3; $i > 0; $i--) { // 3 2 1
1820  $t = $num % $width;
1821  $num /= $width;
1822 
1823  $c[$i] = $t * (256 / $width) + $t * floor(16 / $width);
1824  }
1825 
1826  return $c;
1827  case 'keyword':
1828  $name = $value[1];
1829  if (isset(self::$cssColors[$name])) {
1830  $rgba = explode(',', self::$cssColors[$name]);
1831 
1832  if (isset($rgba[3])) {
1833  return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1834  }
1835  return array('color', $rgba[0], $rgba[1], $rgba[2]);
1836  }
1837  return null;
1838  }
1839  }
1840 
1841  // make something string like into a string
1842  protected function coerceString($value)
1843  {
1844  switch ($value[0]) {
1845  case "string":
1846  return $value;
1847  case "keyword":
1848  return array("string", "", array($value[1]));
1849  }
1850  return null;
1851  }
1852 
1853  // turn list of length 1 into value type
1854  protected function flattenList($value)
1855  {
1856  if ($value[0] == "list" && count($value[2]) == 1) {
1857  return $this->flattenList($value[2][0]);
1858  }
1859  return $value;
1860  }
1861 
1862  public function toBool($a)
1863  {
1864  return $a ? self::$TRUE : self::$FALSE;
1865  }
1866 
1867  // evaluate an expression
1868  protected function evaluate($exp)
1869  {
1870  list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1871 
1872  $left = $this->reduce($left, true);
1873  $right = $this->reduce($right, true);
1874 
1875  if ($leftColor = $this->coerceColor($left)) {
1876  $left = $leftColor;
1877  }
1878 
1879  if ($rightColor = $this->coerceColor($right)) {
1880  $right = $rightColor;
1881  }
1882 
1883  $ltype = $left[0];
1884  $rtype = $right[0];
1885 
1886  // operators that work on all types
1887  if ($op == "and") {
1888  return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
1889  }
1890 
1891  if ($op == "=") {
1892  return $this->toBool($this->eq($left, $right));
1893  }
1894 
1895  if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1896  return $str;
1897  }
1898 
1899  // type based operators
1900  $fname = "op_${ltype}_${rtype}";
1901  if (is_callable(array($this, $fname))) {
1902  $out = $this->$fname($op, $left, $right);
1903  if (!is_null($out)) {
1904  return $out;
1905  }
1906  }
1907 
1908  // make the expression look it did before being parsed
1909  $paddedOp = $op;
1910  if ($whiteBefore) {
1911  $paddedOp = " ".$paddedOp;
1912  }
1913  if ($whiteAfter) {
1914  $paddedOp .= " ";
1915  }
1916 
1917  return array("string", "", array($left, $paddedOp, $right));
1918  }
1919 
1920  protected function stringConcatenate($left, $right)
1921  {
1922  if ($strLeft = $this->coerceString($left)) {
1923  if ($right[0] == "string") {
1924  $right[1] = "";
1925  }
1926  $strLeft[2][] = $right;
1927  return $strLeft;
1928  }
1929 
1930  if ($strRight = $this->coerceString($right)) {
1931  array_unshift($strRight[2], $left);
1932  return $strRight;
1933  }
1934  }
1935 
1936 
1937  // make sure a color's components don't go out of bounds
1938  protected function fixColor($c)
1939  {
1940  foreach (range(1, 3) as $i) {
1941  if ($c[$i] < 0) {
1942  $c[$i] = 0;
1943  }
1944  if ($c[$i] > 255) {
1945  $c[$i] = 255;
1946  }
1947  }
1948 
1949  return $c;
1950  }
1951 
1952  protected function op_number_color($op, $lft, $rgt)
1953  {
1954  if ($op == '+' || $op == '*') {
1955  return $this->op_color_number($op, $rgt, $lft);
1956  }
1957  }
1958 
1959  protected function op_color_number($op, $lft, $rgt)
1960  {
1961  if ($rgt[0] == '%') {
1962  $rgt[1] /= 100;
1963  }
1964 
1965  return $this->op_color_color(
1966  $op,
1967  $lft,
1968  array_fill(1, count($lft) - 1, $rgt[1])
1969  );
1970  }
1971 
1972  protected function op_color_color($op, $left, $right)
1973  {
1974  $out = array('color');
1975  $max = count($left) > count($right) ? count($left) : count($right);
1976  foreach (range(1, $max - 1) as $i) {
1977  $lval = isset($left[$i]) ? $left[$i] : 0;
1978  $rval = isset($right[$i]) ? $right[$i] : 0;
1979  switch ($op) {
1980  case '+':
1981  $out[] = $lval + $rval;
1982  break;
1983  case '-':
1984  $out[] = $lval - $rval;
1985  break;
1986  case '*':
1987  $out[] = $lval * $rval;
1988  break;
1989  case '%':
1990  $out[] = $lval % $rval;
1991  break;
1992  case '/':
1993  if ($rval == 0) {
1994  $this->throwError("evaluate error: can't divide by zero");
1995  }
1996  $out[] = $lval / $rval;
1997  break;
1998  default:
1999  $this->throwError('evaluate error: color op number failed on op '.$op);
2000  }
2001  }
2002  return $this->fixColor($out);
2003  }
2004 
2005  public function lib_red($color)
2006  {
2007  $color = $this->coerceColor($color);
2008  if (is_null($color)) {
2009  $this->throwError('color expected for red()');
2010  }
2011 
2012  return $color[1];
2013  }
2014 
2015  public function lib_green($color)
2016  {
2017  $color = $this->coerceColor($color);
2018  if (is_null($color)) {
2019  $this->throwError('color expected for green()');
2020  }
2021 
2022  return $color[2];
2023  }
2024 
2025  public function lib_blue($color)
2026  {
2027  $color = $this->coerceColor($color);
2028  if (is_null($color)) {
2029  $this->throwError('color expected for blue()');
2030  }
2031 
2032  return $color[3];
2033  }
2034 
2035 
2036  // operator on two numbers
2037  protected function op_number_number($op, $left, $right)
2038  {
2039  $unit = empty($left[2]) ? $right[2] : $left[2];
2040 
2041  $value = 0;
2042  switch ($op) {
2043  case '+':
2044  $value = $left[1] + $right[1];
2045  break;
2046  case '*':
2047  $value = $left[1] * $right[1];
2048  break;
2049  case '-':
2050  $value = $left[1] - $right[1];
2051  break;
2052  case '%':
2053  $value = $left[1] % $right[1];
2054  break;
2055  case '/':
2056  if ($right[1] == 0) {
2057  $this->throwError('parse error: divide by zero');
2058  }
2059  $value = $left[1] / $right[1];
2060  break;
2061  case '<':
2062  return $this->toBool($left[1] < $right[1]);
2063  case '>':
2064  return $this->toBool($left[1] > $right[1]);
2065  case '>=':
2066  return $this->toBool($left[1] >= $right[1]);
2067  case '=<':
2068  return $this->toBool($left[1] <= $right[1]);
2069  default:
2070  $this->throwError('parse error: unknown number operator: '.$op);
2071  }
2072 
2073  return array("number", $value, $unit);
2074  }
2075 
2076 
2077  /* environment functions */
2078 
2079  protected function makeOutputBlock($type, $selectors = null)
2080  {
2081  $b = new stdclass;
2082  $b->lines = array();
2083  $b->children = array();
2084  $b->selectors = $selectors;
2085  $b->type = $type;
2086  $b->parent = $this->scope;
2087  return $b;
2088  }
2089 
2090  // the state of execution
2091  protected function pushEnv($block = null)
2092  {
2093  $e = new stdclass;
2094  $e->parent = $this->env;
2095  $e->store = array();
2096  $e->block = $block;
2097 
2098  $this->env = $e;
2099  return $e;
2100  }
2101 
2102  // pop something off the stack
2103  protected function popEnv()
2104  {
2105  $old = $this->env;
2106  $this->env = $this->env->parent;
2107  return $old;
2108  }
2109 
2110  // set something in the current env
2111  protected function set($name, $value)
2112  {
2113  $this->env->store[$name] = $value;
2114  }
2115 
2116 
2117  // get the highest occurrence entry for a name
2118  protected function get($name)
2119  {
2120  $current = $this->env;
2121 
2122  $isArguments = $name == $this->vPrefix.'arguments';
2123  while ($current) {
2124  if ($isArguments && isset($current->arguments)) {
2125  return array('list', ' ', $current->arguments);
2126  }
2127 
2128  if (isset($current->store[$name])) {
2129  return $current->store[$name];
2130  }
2131 
2132  $current = isset($current->storeParent) ?
2133  $current->storeParent : $current->parent;
2134  }
2135 
2136  $this->throwError("variable $name is undefined");
2137  }
2138 
2139  // inject array of unparsed strings into environment as variables
2140  protected function injectVariables($args)
2141  {
2142  $this->pushEnv();
2143  $parser = new lessc_parser($this, __METHOD__);
2144  foreach ($args as $name => $strValue) {
2145  if ($name[0] !== '@') {
2146  $name = '@'.$name;
2147  }
2148  $parser->count = 0;
2149  $parser->buffer = (string) $strValue;
2150  if (!$parser->propertyValue($value)) {
2151  throw new Exception("failed to parse passed in variable $name: $strValue");
2152  }
2153 
2154  $this->set($name, $value);
2155  }
2156  }
2157 
2162  public function __construct($fname = null)
2163  {
2164  if ($fname !== null) {
2165  // used for deprecated parse method
2166  $this->_parseFile = $fname;
2167  }
2168  }
2169 
2170  public function compile($string, $name = null)
2171  {
2172  $locale = setlocale(LC_NUMERIC, 0);
2173  setlocale(LC_NUMERIC, "C");
2174 
2175  $this->parser = $this->makeParser($name);
2176  $root = $this->parser->parse($string);
2177 
2178  $this->env = null;
2179  $this->scope = null;
2180 
2181  $this->formatter = $this->newFormatter();
2182 
2183  if (!empty($this->registeredVars)) {
2184  $this->injectVariables($this->registeredVars);
2185  }
2186 
2187  $this->sourceParser = $this->parser; // used for error messages
2188  $this->compileBlock($root);
2189 
2190  ob_start();
2191  $this->formatter->block($this->scope);
2192  $out = ob_get_clean();
2193  setlocale(LC_NUMERIC, $locale);
2194  return $out;
2195  }
2196 
2197  public function compileFile($fname, $outFname = null)
2198  {
2199  if (!is_readable($fname)) {
2200  throw new Exception('load error: failed to find '.$fname);
2201  }
2202 
2203  $pi = pathinfo($fname);
2204 
2205  $oldImport = $this->importDir;
2206 
2207  $this->importDir = (array) $this->importDir;
2208  $this->importDir[] = $pi['dirname'].'/';
2209 
2210  $this->addParsedFile($fname);
2211 
2212  $out = $this->compile(file_get_contents($fname), $fname);
2213 
2214  $this->importDir = $oldImport;
2215 
2216  if ($outFname !== null) {
2217  return file_put_contents($outFname, $out);
2218  }
2219 
2220  return $out;
2221  }
2222 
2223  // compile only if changed input has changed or output doesn't exist
2224  public function checkedCompile($in, $out)
2225  {
2226  if (!is_file($out) || filemtime($in) > filemtime($out)) {
2227  $this->compileFile($in, $out);
2228  return true;
2229  }
2230  return false;
2231  }
2232 
2253  public function cachedCompile($in, $force = false)
2254  {
2255  // assume no root
2256  $root = null;
2257 
2258  if (is_string($in)) {
2259  $root = $in;
2260  } elseif (is_array($in) && isset($in['root'])) {
2261  if ($force || !isset($in['files'])) {
2262  // If we are forcing a recompile or if for some reason the
2263  // structure does not contain any file information we should
2264  // specify the root to trigger a rebuild.
2265  $root = $in['root'];
2266  } elseif (isset($in['files']) && is_array($in['files'])) {
2267  foreach ($in['files'] as $fname => $ftime) {
2268  if (!file_exists($fname) || filemtime($fname) > $ftime) {
2269  // One of the files we knew about previously has changed
2270  // so we should look at our incoming root again.
2271  $root = $in['root'];
2272  break;
2273  }
2274  }
2275  }
2276  } else {
2277  // TODO: Throw an exception? We got neither a string nor something
2278  // that looks like a compatible lessphp cache structure.
2279  return null;
2280  }
2281 
2282  if ($root !== null) {
2283  // If we have a root value which means we should rebuild.
2284  $out = array();
2285  $out['root'] = $root;
2286  $out['compiled'] = $this->compileFile($root);
2287  $out['files'] = $this->allParsedFiles();
2288  $out['updated'] = time();
2289  return $out;
2290  } else {
2291  // No changes, pass back the structure
2292  // we were given initially.
2293  return $in;
2294  }
2295  }
2296 
2297  // parse and compile buffer
2298  // This is deprecated
2299  public function parse($str = null, $initialVariables = null)
2300  {
2301  if (is_array($str)) {
2302  $initialVariables = $str;
2303  $str = null;
2304  }
2305 
2306  $oldVars = $this->registeredVars;
2307  if ($initialVariables !== null) {
2308  $this->setVariables($initialVariables);
2309  }
2310 
2311  if ($str == null) {
2312  if (empty($this->_parseFile)) {
2313  throw new exception("nothing to parse");
2314  }
2315 
2316  $out = $this->compileFile($this->_parseFile);
2317  } else {
2318  $out = $this->compile($str);
2319  }
2320 
2321  $this->registeredVars = $oldVars;
2322  return $out;
2323  }
2324 
2325  protected function makeParser($name)
2326  {
2327  $parser = new lessc_parser($this, $name);
2328  $parser->writeComments = $this->preserveComments;
2329 
2330  return $parser;
2331  }
2332 
2333  public function setFormatter($name)
2334  {
2335  $this->formatterName = $name;
2336  }
2337 
2338  protected function newFormatter()
2339  {
2340  $className = "lessc_formatter_lessjs";
2341  if (!empty($this->formatterName)) {
2342  if (!is_string($this->formatterName)) {
2343  return $this->formatterName;
2344  }
2345  $className = "lessc_formatter_$this->formatterName";
2346  }
2347 
2348  return new $className;
2349  }
2350 
2351  public function setPreserveComments($preserve)
2352  {
2353  $this->preserveComments = $preserve;
2354  }
2355 
2356  public function registerFunction($name, $func)
2357  {
2358  $this->libFunctions[$name] = $func;
2359  }
2360 
2361  public function unregisterFunction($name)
2362  {
2363  unset($this->libFunctions[$name]);
2364  }
2365 
2366  public function setVariables($variables)
2367  {
2368  $this->registeredVars = array_merge($this->registeredVars, $variables);
2369  }
2370 
2371  public function unsetVariable($name)
2372  {
2373  unset($this->registeredVars[$name]);
2374  }
2375 
2376  public function setImportDir($dirs)
2377  {
2378  $this->importDir = (array) $dirs;
2379  }
2380 
2381  public function addImportDir($dir)
2382  {
2383  $this->importDir = (array) $this->importDir;
2384  $this->importDir[] = $dir;
2385  }
2386 
2387  public function allParsedFiles()
2388  {
2389  return $this->allParsedFiles;
2390  }
2391 
2392  public function addParsedFile($file)
2393  {
2394  $this->allParsedFiles[realpath($file)] = filemtime($file);
2395  }
2396 
2400  public function throwError($msg = null)
2401  {
2402  if ($this->sourceLoc >= 0) {
2403  $this->sourceParser->throwError($msg, $this->sourceLoc);
2404  }
2405  throw new exception($msg);
2406  }
2407 
2408  // compile file $in to file $out if $in is newer than $out
2409  // returns true when it compiles, false otherwise
2410  public static function ccompile($in, $out, $less = null)
2411  {
2412  if ($less === null) {
2413  $less = new self;
2414  }
2415  return $less->checkedCompile($in, $out);
2416  }
2417 
2418  public static function cexecute($in, $force = false, $less = null)
2419  {
2420  if ($less === null) {
2421  $less = new self;
2422  }
2423  return $less->cachedCompile($in, $force);
2424  }
2425 
2426  protected static $cssColors = array(
2427  'aliceblue' => '240,248,255',
2428  'antiquewhite' => '250,235,215',
2429  'aqua' => '0,255,255',
2430  'aquamarine' => '127,255,212',
2431  'azure' => '240,255,255',
2432  'beige' => '245,245,220',
2433  'bisque' => '255,228,196',
2434  'black' => '0,0,0',
2435  'blanchedalmond' => '255,235,205',
2436  'blue' => '0,0,255',
2437  'blueviolet' => '138,43,226',
2438  'brown' => '165,42,42',
2439  'burlywood' => '222,184,135',
2440  'cadetblue' => '95,158,160',
2441  'chartreuse' => '127,255,0',
2442  'chocolate' => '210,105,30',
2443  'coral' => '255,127,80',
2444  'cornflowerblue' => '100,149,237',
2445  'cornsilk' => '255,248,220',
2446  'crimson' => '220,20,60',
2447  'cyan' => '0,255,255',
2448  'darkblue' => '0,0,139',
2449  'darkcyan' => '0,139,139',
2450  'darkgoldenrod' => '184,134,11',
2451  'darkgray' => '169,169,169',
2452  'darkgreen' => '0,100,0',
2453  'darkgrey' => '169,169,169',
2454  'darkkhaki' => '189,183,107',
2455  'darkmagenta' => '139,0,139',
2456  'darkolivegreen' => '85,107,47',
2457  'darkorange' => '255,140,0',
2458  'darkorchid' => '153,50,204',
2459  'darkred' => '139,0,0',
2460  'darksalmon' => '233,150,122',
2461  'darkseagreen' => '143,188,143',
2462  'darkslateblue' => '72,61,139',
2463  'darkslategray' => '47,79,79',
2464  'darkslategrey' => '47,79,79',
2465  'darkturquoise' => '0,206,209',
2466  'darkviolet' => '148,0,211',
2467  'deeppink' => '255,20,147',
2468  'deepskyblue' => '0,191,255',
2469  'dimgray' => '105,105,105',
2470  'dimgrey' => '105,105,105',
2471  'dodgerblue' => '30,144,255',
2472  'firebrick' => '178,34,34',
2473  'floralwhite' => '255,250,240',
2474  'forestgreen' => '34,139,34',
2475  'fuchsia' => '255,0,255',
2476  'gainsboro' => '220,220,220',
2477  'ghostwhite' => '248,248,255',
2478  'gold' => '255,215,0',
2479  'goldenrod' => '218,165,32',
2480  'gray' => '128,128,128',
2481  'green' => '0,128,0',
2482  'greenyellow' => '173,255,47',
2483  'grey' => '128,128,128',
2484  'honeydew' => '240,255,240',
2485  'hotpink' => '255,105,180',
2486  'indianred' => '205,92,92',
2487  'indigo' => '75,0,130',
2488  'ivory' => '255,255,240',
2489  'khaki' => '240,230,140',
2490  'lavender' => '230,230,250',
2491  'lavenderblush' => '255,240,245',
2492  'lawngreen' => '124,252,0',
2493  'lemonchiffon' => '255,250,205',
2494  'lightblue' => '173,216,230',
2495  'lightcoral' => '240,128,128',
2496  'lightcyan' => '224,255,255',
2497  'lightgoldenrodyellow' => '250,250,210',
2498  'lightgray' => '211,211,211',
2499  'lightgreen' => '144,238,144',
2500  'lightgrey' => '211,211,211',
2501  'lightpink' => '255,182,193',
2502  'lightsalmon' => '255,160,122',
2503  'lightseagreen' => '32,178,170',
2504  'lightskyblue' => '135,206,250',
2505  'lightslategray' => '119,136,153',
2506  'lightslategrey' => '119,136,153',
2507  'lightsteelblue' => '176,196,222',
2508  'lightyellow' => '255,255,224',
2509  'lime' => '0,255,0',
2510  'limegreen' => '50,205,50',
2511  'linen' => '250,240,230',
2512  'magenta' => '255,0,255',
2513  'maroon' => '128,0,0',
2514  'mediumaquamarine' => '102,205,170',
2515  'mediumblue' => '0,0,205',
2516  'mediumorchid' => '186,85,211',
2517  'mediumpurple' => '147,112,219',
2518  'mediumseagreen' => '60,179,113',
2519  'mediumslateblue' => '123,104,238',
2520  'mediumspringgreen' => '0,250,154',
2521  'mediumturquoise' => '72,209,204',
2522  'mediumvioletred' => '199,21,133',
2523  'midnightblue' => '25,25,112',
2524  'mintcream' => '245,255,250',
2525  'mistyrose' => '255,228,225',
2526  'moccasin' => '255,228,181',
2527  'navajowhite' => '255,222,173',
2528  'navy' => '0,0,128',
2529  'oldlace' => '253,245,230',
2530  'olive' => '128,128,0',
2531  'olivedrab' => '107,142,35',
2532  'orange' => '255,165,0',
2533  'orangered' => '255,69,0',
2534  'orchid' => '218,112,214',
2535  'palegoldenrod' => '238,232,170',
2536  'palegreen' => '152,251,152',
2537  'paleturquoise' => '175,238,238',
2538  'palevioletred' => '219,112,147',
2539  'papayawhip' => '255,239,213',
2540  'peachpuff' => '255,218,185',
2541  'peru' => '205,133,63',
2542  'pink' => '255,192,203',
2543  'plum' => '221,160,221',
2544  'powderblue' => '176,224,230',
2545  'purple' => '128,0,128',
2546  'red' => '255,0,0',
2547  'rosybrown' => '188,143,143',
2548  'royalblue' => '65,105,225',
2549  'saddlebrown' => '139,69,19',
2550  'salmon' => '250,128,114',
2551  'sandybrown' => '244,164,96',
2552  'seagreen' => '46,139,87',
2553  'seashell' => '255,245,238',
2554  'sienna' => '160,82,45',
2555  'silver' => '192,192,192',
2556  'skyblue' => '135,206,235',
2557  'slateblue' => '106,90,205',
2558  'slategray' => '112,128,144',
2559  'slategrey' => '112,128,144',
2560  'snow' => '255,250,250',
2561  'springgreen' => '0,255,127',
2562  'steelblue' => '70,130,180',
2563  'tan' => '210,180,140',
2564  'teal' => '0,128,128',
2565  'thistle' => '216,191,216',
2566  'tomato' => '255,99,71',
2567  'transparent' => '0,0,0,0',
2568  'turquoise' => '64,224,208',
2569  'violet' => '238,130,238',
2570  'wheat' => '245,222,179',
2571  'white' => '255,255,255',
2572  'whitesmoke' => '245,245,245',
2573  'yellow' => '255,255,0',
2574  'yellowgreen' => '154,205,50'
2575  );
2576 }
2577 
2578 // responsible for taking a string of LESS code and converting it into a
2579 // syntax tree
2581 {
2582  protected static $nextBlockId = 0; // used to uniquely identify blocks
2583 
2584  protected static $precedence = array(
2585  '=<' => 0,
2586  '>=' => 0,
2587  '=' => 0,
2588  '<' => 0,
2589  '>' => 0,
2590 
2591  '+' => 1,
2592  '-' => 1,
2593  '*' => 2,
2594  '/' => 2,
2595  '%' => 2,
2596  );
2597 
2598  protected static $whitePattern;
2599  protected static $commentMulti;
2600 
2601  protected static $commentSingle = "//";
2602  protected static $commentMultiLeft = "/*";
2603  protected static $commentMultiRight = "*/";
2604 
2605  // regex string to match any of the operators
2606  protected static $operatorString;
2607 
2608  // these properties will supress division unless it's inside parenthases
2609  protected static $supressDivisionProps =
2610  array('/border-radius$/i', '/^font$/i');
2611 
2612  protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
2613  protected $lineDirectives = array("charset");
2614 
2624  protected $inParens = false;
2625 
2626  // caches preg escaped literals
2627  protected static $literalCache = array();
2628 
2629  public function __construct($lessc, $sourceName = null)
2630  {
2631  $this->eatWhiteDefault = true;
2632  // reference to less needed for vPrefix, mPrefix, and parentSelector
2633  $this->lessc = $lessc;
2634 
2635  $this->sourceName = $sourceName; // name used for error messages
2636 
2637  $this->writeComments = false;
2638 
2639  if (!self::$operatorString) {
2640  self::$operatorString =
2641  '('.implode('|', array_map(
2642  array('lessc', 'preg_quote'),
2643  array_keys(self::$precedence)
2644  )).')';
2645 
2646  $commentSingle = lessc::preg_quote(self::$commentSingle);
2647  $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
2648  $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
2649 
2650  self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
2651  self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
2652  }
2653  }
2654 
2662  public function parse($buffer)
2663  {
2664  $this->count = 0;
2665  $this->line = 1;
2666 
2667  $this->env = null; // block stack
2668  $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
2669  $this->pushSpecialBlock("root");
2670  $this->eatWhiteDefault = true;
2671  $this->seenComments = array();
2672 
2673  // trim whitespace on head
2674  // if (preg_match('/^\s+/', $this->buffer, $m)) {
2675  // $this->line += substr_count($m[0], "\n");
2676  // $this->buffer = ltrim($this->buffer);
2677  // }
2678  $this->whitespace();
2679 
2680  // parse the entire file
2681  while (false !== $this->parseChunk());
2682 
2683  if ($this->count != strlen($this->buffer)) {
2684  $this->throwError('parse error count '.$this->count.' != len buffer '.strlen($this->buffer));
2685  }
2686 
2687  // TODO report where the block was opened
2688  if (!property_exists($this->env, 'parent') || !is_null($this->env->parent)) {
2689  throw new exception('parse error: unclosed block');
2690  }
2691 
2692  return $this->env;
2693  }
2694 
2731  protected function parseChunk()
2732  {
2733  if (empty($this->buffer)) {
2734  return false;
2735  }
2736  $s = $this->seek();
2737 
2738  if ($this->whitespace()) {
2739  return true;
2740  }
2741 
2742  // setting a property
2743  if ($this->keyword($key) && $this->assign() &&
2744  $this->propertyValue($value, $key) && $this->end()
2745  ) {
2746  $this->append(array('assign', $key, $value), $s);
2747  return true;
2748  } else {
2749  $this->seek($s);
2750  }
2751 
2752 
2753  // look for special css blocks
2754  if ($this->literal('@', false)) {
2755  $this->count--;
2756 
2757  // media
2758  if ($this->literal('@media')) {
2759  if (($this->mediaQueryList($mediaQueries) || true)
2760  && $this->literal('{')
2761  ) {
2762  $media = $this->pushSpecialBlock("media");
2763  $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
2764  return true;
2765  } else {
2766  $this->seek($s);
2767  return false;
2768  }
2769  }
2770 
2771  if ($this->literal("@", false) && $this->keyword($dirName)) {
2772  if ($this->isDirective($dirName, $this->blockDirectives)) {
2773  if (($this->openString("{", $dirValue, null, array(";")) || true) &&
2774  $this->literal("{")
2775  ) {
2776  $dir = $this->pushSpecialBlock("directive");
2777  $dir->name = $dirName;
2778  if (isset($dirValue)) {
2779  $dir->value = $dirValue;
2780  }
2781  return true;
2782  }
2783  } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
2784  if ($this->propertyValue($dirValue) && $this->end()) {
2785  $this->append(array("directive", $dirName, $dirValue));
2786  return true;
2787  }
2788  }
2789  }
2790 
2791  $this->seek($s);
2792  }
2793 
2794  // setting a variable
2795  if ($this->variable($var) && $this->assign() &&
2796  $this->propertyValue($value) && $this->end()
2797  ) {
2798  $this->append(array('assign', $var, $value), $s);
2799  return true;
2800  } else {
2801  $this->seek($s);
2802  }
2803 
2804  if ($this->import($importValue)) {
2805  $this->append($importValue, $s);
2806  return true;
2807  }
2808 
2809  // opening parametric mixin
2810  if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
2811  ($this->guards($guards) || true) &&
2812  $this->literal('{')
2813  ) {
2814  $block = $this->pushBlock($this->fixTags(array($tag)));
2815  $block->args = $args;
2816  $block->isVararg = $isVararg;
2817  if (!empty($guards)) {
2818  $block->guards = $guards;
2819  }
2820  return true;
2821  } else {
2822  $this->seek($s);
2823  }
2824 
2825  // opening a simple block
2826  if ($this->tags($tags) && $this->literal('{', false)) {
2827  $tags = $this->fixTags($tags);
2828  $this->pushBlock($tags);
2829  return true;
2830  } else {
2831  $this->seek($s);
2832  }
2833 
2834  // closing a block
2835  if ($this->literal('}', false)) {
2836  try {
2837  $block = $this->pop();
2838  } catch (exception $e) {
2839  $this->seek($s);
2840  $this->throwError($e->getMessage());
2841  }
2842 
2843  $hidden = false;
2844  if (is_null($block->type)) {
2845  $hidden = true;
2846  if (!isset($block->args)) {
2847  foreach ($block->tags as $tag) {
2848  if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
2849  $hidden = false;
2850  break;
2851  }
2852  }
2853  }
2854 
2855  foreach ($block->tags as $tag) {
2856  if (is_string($tag)) {
2857  $this->env->children[$tag][] = $block;
2858  }
2859  }
2860  }
2861 
2862  if (!$hidden) {
2863  $this->append(array('block', $block), $s);
2864  }
2865 
2866  // this is done here so comments aren't bundled into he block that
2867  // was just closed
2868  $this->whitespace();
2869  return true;
2870  }
2871 
2872  // mixin
2873  if ($this->mixinTags($tags) &&
2874  ($this->argumentDef($argv, $isVararg) || true) &&
2875  ($this->keyword($suffix) || true) && $this->end()
2876  ) {
2877  $tags = $this->fixTags($tags);
2878  $this->append(array('mixin', $tags, $argv, $suffix), $s);
2879  return true;
2880  } else {
2881  $this->seek($s);
2882  }
2883 
2884  // spare ;
2885  if ($this->literal(';')) {
2886  return true;
2887  }
2888 
2889  return false; // got nothing, throw error
2890  }
2891 
2892  protected function isDirective($dirname, $directives)
2893  {
2894  // TODO: cache pattern in parser
2895  $pattern = implode(
2896  "|",
2897  array_map(array("lessc", "preg_quote"), $directives)
2898  );
2899  $pattern = '/^(-[a-z-]+-)?('.$pattern.')$/i';
2900 
2901  return preg_match($pattern, $dirname);
2902  }
2903 
2904  protected function fixTags($tags)
2905  {
2906  // move @ tags out of variable namespace
2907  foreach ($tags as &$tag) {
2908  if ($tag[0] == $this->lessc->vPrefix) {
2909  $tag[0] = $this->lessc->mPrefix;
2910  }
2911  }
2912  return $tags;
2913  }
2914 
2915  // a list of expressions
2916  protected function expressionList(&$exps)
2917  {
2918  $values = array();
2919 
2920  while ($this->expression($exp)) {
2921  $values[] = $exp;
2922  }
2923 
2924  if (count($values) == 0) {
2925  return false;
2926  }
2927 
2928  $exps = lessc::compressList($values, ' ');
2929  return true;
2930  }
2931 
2936  protected function expression(&$out)
2937  {
2938  if ($this->value($lhs)) {
2939  $out = $this->expHelper($lhs, 0);
2940 
2941  // look for / shorthand
2942  if (!empty($this->env->supressedDivision)) {
2943  unset($this->env->supressedDivision);
2944  $s = $this->seek();
2945  if ($this->literal("/") && $this->value($rhs)) {
2946  $out = array("list", "",
2947  array($out, array("keyword", "/"), $rhs));
2948  } else {
2949  $this->seek($s);
2950  }
2951  }
2952 
2953  return true;
2954  }
2955  return false;
2956  }
2957 
2961  protected function expHelper($lhs, $minP)
2962  {
2963  $this->inExp = true;
2964  $ss = $this->seek();
2965 
2966  while (true) {
2967  $whiteBefore = isset($this->buffer[$this->count - 1]) &&
2968  ctype_space($this->buffer[$this->count - 1]);
2969 
2970  // If there is whitespace before the operator, then we require
2971  // whitespace after the operator for it to be an expression
2972  $needWhite = $whiteBefore && !$this->inParens;
2973 
2974  if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
2975  if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
2976  foreach (self::$supressDivisionProps as $pattern) {
2977  if (preg_match($pattern, $this->env->currentProperty)) {
2978  $this->env->supressedDivision = true;
2979  break 2;
2980  }
2981  }
2982  }
2983 
2984 
2985  $whiteAfter = isset($this->buffer[$this->count - 1]) &&
2986  ctype_space($this->buffer[$this->count - 1]);
2987 
2988  if (!$this->value($rhs)) {
2989  break;
2990  }
2991 
2992  // peek for next operator to see what to do with rhs
2993  if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
2994  $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
2995  }
2996 
2997  $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
2998  $ss = $this->seek();
2999 
3000  continue;
3001  }
3002 
3003  break;
3004  }
3005 
3006  $this->seek($ss);
3007 
3008  return $lhs;
3009  }
3010 
3011  // consume a list of values for a property
3012  public function propertyValue(&$value, $keyName = null)
3013  {
3014  $values = array();
3015 
3016  if ($keyName !== null) {
3017  $this->env->currentProperty = $keyName;
3018  }
3019 
3020  $s = null;
3021  while ($this->expressionList($v)) {
3022  $values[] = $v;
3023  $s = $this->seek();
3024  if (!$this->literal(',')) {
3025  break;
3026  }
3027  }
3028 
3029  if ($s) {
3030  $this->seek($s);
3031  }
3032 
3033  if ($keyName !== null) {
3034  unset($this->env->currentProperty);
3035  }
3036 
3037  if (count($values) == 0) {
3038  return false;
3039  }
3040 
3041  $value = lessc::compressList($values, ', ');
3042  return true;
3043  }
3044 
3045  protected function parenValue(&$out)
3046  {
3047  $s = $this->seek();
3048 
3049  // speed shortcut
3050  if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
3051  return false;
3052  }
3053 
3055  if ($this->literal("(") &&
3056  ($this->inParens = true) && $this->expression($exp) &&
3057  $this->literal(")")
3058  ) {
3059  $out = $exp;
3060  $this->inParens = $inParens;
3061  return true;
3062  } else {
3063  $this->inParens = $inParens;
3064  $this->seek($s);
3065  }
3066 
3067  return false;
3068  }
3069 
3070  // a single value
3071  protected function value(&$value)
3072  {
3073  $s = $this->seek();
3074 
3075  // speed shortcut
3076  if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
3077  // negation
3078  if ($this->literal("-", false) &&
3079  (($this->variable($inner) && $inner = array("variable", $inner)) ||
3080  $this->unit($inner) ||
3081  $this->parenValue($inner))
3082  ) {
3083  $value = array("unary", "-", $inner);
3084  return true;
3085  } else {
3086  $this->seek($s);
3087  }
3088  }
3089 
3090  if ($this->parenValue($value)) {
3091  return true;
3092  }
3093  if ($this->unit($value)) {
3094  return true;
3095  }
3096  if ($this->color($value)) {
3097  return true;
3098  }
3099  if ($this->func($value)) {
3100  return true;
3101  }
3102  if ($this->string($value)) {
3103  return true;
3104  }
3105 
3106  if ($this->keyword($word)) {
3107  $value = array('keyword', $word);
3108  return true;
3109  }
3110 
3111  // try a variable
3112  if ($this->variable($var)) {
3113  $value = array('variable', $var);
3114  return true;
3115  }
3116 
3117  // unquote string (should this work on any type?
3118  if ($this->literal("~") && $this->string($str)) {
3119  $value = array("escape", $str);
3120  return true;
3121  } else {
3122  $this->seek($s);
3123  }
3124 
3125  // css hack: \0
3126  if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
3127  $value = array('keyword', '\\'.$m[1]);
3128  return true;
3129  } else {
3130  $this->seek($s);
3131  }
3132 
3133  return false;
3134  }
3135 
3136  // an import statement
3137  protected function import(&$out)
3138  {
3139  if (!$this->literal('@import')) {
3140  return false;
3141  }
3142 
3143  // @import "something.css" media;
3144  // @import url("something.css") media;
3145  // @import url(something.css) media;
3146 
3147  if ($this->propertyValue($value)) {
3148  $out = array("import", $value);
3149  return true;
3150  }
3151  }
3152 
3153  protected function mediaQueryList(&$out)
3154  {
3155  if ($this->genericList($list, "mediaQuery", ",", false)) {
3156  $out = $list[2];
3157  return true;
3158  }
3159  return false;
3160  }
3161 
3162  protected function mediaQuery(&$out)
3163  {
3164  $s = $this->seek();
3165 
3166  $expressions = null;
3167  $parts = array();
3168 
3169  if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) {
3170  $prop = array("mediaType");
3171  if (isset($only)) {
3172  $prop[] = "only";
3173  }
3174  if (isset($not)) {
3175  $prop[] = "not";
3176  }
3177  $prop[] = $mediaType;
3178  $parts[] = $prop;
3179  } else {
3180  $this->seek($s);
3181  }
3182 
3183 
3184  if (!empty($mediaType) && !$this->literal("and")) {
3185  // ~
3186  } else {
3187  $this->genericList($expressions, "mediaExpression", "and", false);
3188  if (is_array($expressions)) {
3189  $parts = array_merge($parts, $expressions[2]);
3190  }
3191  }
3192 
3193  if (count($parts) == 0) {
3194  $this->seek($s);
3195  return false;
3196  }
3197 
3198  $out = $parts;
3199  return true;
3200  }
3201 
3202  protected function mediaExpression(&$out)
3203  {
3204  $s = $this->seek();
3205  $value = null;
3206  if ($this->literal("(") &&
3207  $this->keyword($feature) &&
3208  ($this->literal(":") && $this->expression($value) || true) &&
3209  $this->literal(")")
3210  ) {
3211  $out = array("mediaExp", $feature);
3212  if ($value) {
3213  $out[] = $value;
3214  }
3215  return true;
3216  } elseif ($this->variable($variable)) {
3217  $out = array('variable', $variable);
3218  return true;
3219  }
3220 
3221  $this->seek($s);
3222  return false;
3223  }
3224 
3225  // an unbounded string stopped by $end
3226  protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null)
3227  {
3228  $oldWhite = $this->eatWhiteDefault;
3229  $this->eatWhiteDefault = false;
3230 
3231  $stop = array("'", '"', "@{", $end);
3232  $stop = array_map(array("lessc", "preg_quote"), $stop);
3233  // $stop[] = self::$commentMulti;
3234 
3235  if (!is_null($rejectStrs)) {
3236  $stop = array_merge($stop, $rejectStrs);
3237  }
3238 
3239  $patt = '(.*?)('.implode("|", $stop).')';
3240 
3241  $nestingLevel = 0;
3242 
3243  $content = array();
3244  while ($this->match($patt, $m, false)) {
3245  if (!empty($m[1])) {
3246  $content[] = $m[1];
3247  if ($nestingOpen) {
3248  $nestingLevel += substr_count($m[1], $nestingOpen);
3249  }
3250  }
3251 
3252  $tok = $m[2];
3253 
3254  $this->count -= strlen($tok);
3255  if ($tok == $end) {
3256  if ($nestingLevel == 0) {
3257  break;
3258  } else {
3259  $nestingLevel--;
3260  }
3261  }
3262 
3263  if (($tok == "'" || $tok == '"') && $this->string($str)) {
3264  $content[] = $str;
3265  continue;
3266  }
3267 
3268  if ($tok == "@{" && $this->interpolation($inter)) {
3269  $content[] = $inter;
3270  continue;
3271  }
3272 
3273  if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
3274  break;
3275  }
3276 
3277  $content[] = $tok;
3278  $this->count += strlen($tok);
3279  }
3280 
3281  $this->eatWhiteDefault = $oldWhite;
3282 
3283  if (count($content) == 0) {
3284  return false;
3285  }
3286 
3287  // trim the end
3288  if (is_string(end($content))) {
3289  $content[count($content) - 1] = rtrim(end($content));
3290  }
3291 
3292  $out = array("string", "", $content);
3293  return true;
3294  }
3295 
3296  protected function string(&$out)
3297  {
3298  $s = $this->seek();
3299  if ($this->literal('"', false)) {
3300  $delim = '"';
3301  } elseif ($this->literal("'", false)) {
3302  $delim = "'";
3303  } else {
3304  return false;
3305  }
3306 
3307  $content = array();
3308 
3309  // look for either ending delim , escape, or string interpolation
3310  $patt = '([^\n]*?)(@\{|\\\\|'.
3311  lessc::preg_quote($delim).')';
3312 
3313  $oldWhite = $this->eatWhiteDefault;
3314  $this->eatWhiteDefault = false;
3315 
3316  while ($this->match($patt, $m, false)) {
3317  $content[] = $m[1];
3318  if ($m[2] == "@{") {
3319  $this->count -= strlen($m[2]);
3320  if ($this->interpolation($inter)) {
3321  $content[] = $inter;
3322  } else {
3323  $this->count += strlen($m[2]);
3324  $content[] = "@{"; // ignore it
3325  }
3326  } elseif ($m[2] == '\\') {
3327  $content[] = $m[2];
3328  if ($this->literal($delim, false)) {
3329  $content[] = $delim;
3330  }
3331  } else {
3332  $this->count -= strlen($delim);
3333  break; // delim
3334  }
3335  }
3336 
3337  $this->eatWhiteDefault = $oldWhite;
3338 
3339  if ($this->literal($delim)) {
3340  $out = array("string", $delim, $content);
3341  return true;
3342  }
3343 
3344  $this->seek($s);
3345  return false;
3346  }
3347 
3348  protected function interpolation(&$out)
3349  {
3350  $oldWhite = $this->eatWhiteDefault;
3351  $this->eatWhiteDefault = true;
3352 
3353  $s = $this->seek();
3354  if ($this->literal("@{") &&
3355  $this->openString("}", $interp, null, array("'", '"', ";")) &&
3356  $this->literal("}", false)
3357  ) {
3358  $out = array("interpolate", $interp);
3359  $this->eatWhiteDefault = $oldWhite;
3360  if ($this->eatWhiteDefault) {
3361  $this->whitespace();
3362  }
3363  return true;
3364  }
3365 
3366  $this->eatWhiteDefault = $oldWhite;
3367  $this->seek($s);
3368  return false;
3369  }
3370 
3371  protected function unit(&$unit)
3372  {
3373  // speed shortcut
3374  if (isset($this->buffer[$this->count])) {
3375  $char = $this->buffer[$this->count];
3376  if (!ctype_digit($char) && $char != ".") {
3377  return false;
3378  }
3379  }
3380 
3381  if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
3382  $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
3383  return true;
3384  }
3385  return false;
3386  }
3387 
3388  // a # color
3389  protected function color(&$out)
3390  {
3391  if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
3392  if (strlen($m[1]) > 7) {
3393  $out = array("string", "", array($m[1]));
3394  } else {
3395  $out = array("raw_color", $m[1]);
3396  }
3397  return true;
3398  }
3399 
3400  return false;
3401  }
3402 
3403  // consume an argument definition list surrounded by ()
3404  // each argument is a variable name with optional value
3405  // or at the end a ... or a variable named followed by ...
3406  // arguments are separated by , unless a ; is in the list, then ; is the
3407  // delimiter.
3408  protected function argumentDef(&$args, &$isVararg)
3409  {
3410  $s = $this->seek();
3411  if (!$this->literal('(')) {
3412  return false;
3413  }
3414 
3415  $values = array();
3416  $delim = ",";
3417  $method = "expressionList";
3418 
3419  $isVararg = false;
3420  while (true) {
3421  if ($this->literal("...")) {
3422  $isVararg = true;
3423  break;
3424  }
3425 
3426  if ($this->$method($value)) {
3427  if ($value[0] == "variable") {
3428  $arg = array("arg", $value[1]);
3429  $ss = $this->seek();
3430 
3431  if ($this->assign() && $this->$method($rhs)) {
3432  $arg[] = $rhs;
3433  } else {
3434  $this->seek($ss);
3435  if ($this->literal("...")) {
3436  $arg[0] = "rest";
3437  $isVararg = true;
3438  }
3439  }
3440 
3441  $values[] = $arg;
3442  if ($isVararg) {
3443  break;
3444  }
3445  continue;
3446  } else {
3447  $values[] = array("lit", $value);
3448  }
3449  }
3450 
3451 
3452  if (!$this->literal($delim)) {
3453  if ($delim == "," && $this->literal(";")) {
3454  // found new delim, convert existing args
3455  $delim = ";";
3456  $method = "propertyValue";
3457 
3458  // transform arg list
3459  if (isset($values[1])) { // 2 items
3460  $newList = array();
3461  foreach ($values as $i => $arg) {
3462  switch ($arg[0]) {
3463  case "arg":
3464  if ($i) {
3465  $this->throwError("Cannot mix ; and , as delimiter types");
3466  }
3467  $newList[] = $arg[2];
3468  break;
3469  case "lit":
3470  $newList[] = $arg[1];
3471  break;
3472  case "rest":
3473  $this->throwError("Unexpected rest before semicolon");
3474  }
3475  }
3476 
3477  $newList = array("list", ", ", $newList);
3478 
3479  switch ($values[0][0]) {
3480  case "arg":
3481  $newArg = array("arg", $values[0][1], $newList);
3482  break;
3483  case "lit":
3484  $newArg = array("lit", $newList);
3485  break;
3486  }
3487  } elseif ($values) { // 1 item
3488  $newArg = $values[0];
3489  }
3490 
3491  if ($newArg) {
3492  $values = array($newArg);
3493  }
3494  } else {
3495  break;
3496  }
3497  }
3498  }
3499 
3500  if (!$this->literal(')')) {
3501  $this->seek($s);
3502  return false;
3503  }
3504 
3505  $args = $values;
3506 
3507  return true;
3508  }
3509 
3510  // consume a list of tags
3511  // this accepts a hanging delimiter
3512  protected function tags(&$tags, $simple = false, $delim = ',')
3513  {
3514  $tags = array();
3515  while ($this->tag($tt, $simple)) {
3516  $tags[] = $tt;
3517  if (!$this->literal($delim)) {
3518  break;
3519  }
3520  }
3521  if (count($tags) == 0) {
3522  return false;
3523  }
3524 
3525  return true;
3526  }
3527 
3528  // list of tags of specifying mixin path
3529  // optionally separated by > (lazy, accepts extra >)
3530  protected function mixinTags(&$tags)
3531  {
3532  $tags = array();
3533  while ($this->tag($tt, true)) {
3534  $tags[] = $tt;
3535  $this->literal(">");
3536  }
3537 
3538  if (!$tags) {
3539  return false;
3540  }
3541 
3542  return true;
3543  }
3544 
3545  // a bracketed value (contained within in a tag definition)
3546  protected function tagBracket(&$parts, &$hasExpression)
3547  {
3548  // speed shortcut
3549  if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
3550  return false;
3551  }
3552 
3553  $s = $this->seek();
3554 
3555  $hasInterpolation = false;
3556 
3557  if ($this->literal("[", false)) {
3558  $attrParts = array("[");
3559  // keyword, string, operator
3560  while (true) {
3561  if ($this->literal("]", false)) {
3562  $this->count--;
3563  break; // get out early
3564  }
3565 
3566  if ($this->match('\s+', $m)) {
3567  $attrParts[] = " ";
3568  continue;
3569  }
3570  if ($this->string($str)) {
3571  // escape parent selector, (yuck)
3572  foreach ($str[2] as &$chunk) {
3573  $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
3574  }
3575 
3576  $attrParts[] = $str;
3577  $hasInterpolation = true;
3578  continue;
3579  }
3580 
3581  if ($this->keyword($word)) {
3582  $attrParts[] = $word;
3583  continue;
3584  }
3585 
3586  if ($this->interpolation($inter)) {
3587  $attrParts[] = $inter;
3588  $hasInterpolation = true;
3589  continue;
3590  }
3591 
3592  // operator, handles attr namespace too
3593  if ($this->match('[|-~\$\*\^=]+', $m)) {
3594  $attrParts[] = $m[0];
3595  continue;
3596  }
3597 
3598  break;
3599  }
3600 
3601  if ($this->literal("]", false)) {
3602  $attrParts[] = "]";
3603  foreach ($attrParts as $part) {
3604  $parts[] = $part;
3605  }
3606  $hasExpression = $hasExpression || $hasInterpolation;
3607  return true;
3608  }
3609  $this->seek($s);
3610  }
3611 
3612  $this->seek($s);
3613  return false;
3614  }
3615 
3616  // a space separated list of selectors
3617  protected function tag(&$tag, $simple = false)
3618  {
3619  if ($simple) {
3620  $chars = '^@,:;{}\][>\(\) "\'';
3621  } else {
3622  $chars = '^@,;{}["\'';
3623  }
3624  $s = $this->seek();
3625 
3626  $hasExpression = false;
3627  $parts = array();
3628  while ($this->tagBracket($parts, $hasExpression));
3629 
3630  $oldWhite = $this->eatWhiteDefault;
3631  $this->eatWhiteDefault = false;
3632 
3633  while (true) {
3634  if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
3635  $parts[] = $m[1];
3636  if ($simple) {
3637  break;
3638  }
3639 
3640  while ($this->tagBracket($parts, $hasExpression));
3641  continue;
3642  }
3643 
3644  if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
3645  if ($this->interpolation($interp)) {
3646  $hasExpression = true;
3647  $interp[2] = true; // don't unescape
3648  $parts[] = $interp;
3649  continue;
3650  }
3651 
3652  if ($this->literal("@")) {
3653  $parts[] = "@";
3654  continue;
3655  }
3656  }
3657 
3658  if ($this->unit($unit)) { // for keyframes
3659  $parts[] = $unit[1];
3660  $parts[] = $unit[2];
3661  continue;
3662  }
3663 
3664  break;
3665  }
3666 
3667  $this->eatWhiteDefault = $oldWhite;
3668  if (!$parts) {
3669  $this->seek($s);
3670  return false;
3671  }
3672 
3673  if ($hasExpression) {
3674  $tag = array("exp", array("string", "", $parts));
3675  } else {
3676  $tag = trim(implode($parts));
3677  }
3678 
3679  $this->whitespace();
3680  return true;
3681  }
3682 
3683  // a css function
3684  protected function func(&$func)
3685  {
3686  $s = $this->seek();
3687 
3688  if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
3689  $fname = $m[1];
3690 
3691  $sPreArgs = $this->seek();
3692 
3693  $args = array();
3694  while (true) {
3695  $ss = $this->seek();
3696  // this ugly nonsense is for ie filter properties
3697  if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
3698  $args[] = array("string", "", array($name, "=", $value));
3699  } else {
3700  $this->seek($ss);
3701  if ($this->expressionList($value)) {
3702  $args[] = $value;
3703  }
3704  }
3705 
3706  if (!$this->literal(',')) {
3707  break;
3708  }
3709  }
3710  $args = array('list', ',', $args);
3711 
3712  if ($this->literal(')')) {
3713  $func = array('function', $fname, $args);
3714  return true;
3715  } elseif ($fname == 'url') {
3716  // couldn't parse and in url? treat as string
3717  $this->seek($sPreArgs);
3718  if ($this->openString(")", $string) && $this->literal(")")) {
3719  $func = array('function', $fname, $string);
3720  return true;
3721  }
3722  }
3723  }
3724 
3725  $this->seek($s);
3726  return false;
3727  }
3728 
3729  // consume a less variable
3730  protected function variable(&$name)
3731  {
3732  $s = $this->seek();
3733  if ($this->literal($this->lessc->vPrefix, false) &&
3734  ($this->variable($sub) || $this->keyword($name))
3735  ) {
3736  if (!empty($sub)) {
3737  $name = array('variable', $sub);
3738  } else {
3739  $name = $this->lessc->vPrefix.$name;
3740  }
3741  return true;
3742  }
3743 
3744  $name = null;
3745  $this->seek($s);
3746  return false;
3747  }
3748 
3753  protected function assign($name = null)
3754  {
3755  if ($name) {
3756  $this->currentProperty = $name;
3757  }
3758  return $this->literal(':') || $this->literal('=');
3759  }
3760 
3761  // consume a keyword
3762  protected function keyword(&$word)
3763  {
3764  if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
3765  $word = $m[1];
3766  return true;
3767  }
3768  return false;
3769  }
3770 
3771  // consume an end of statement delimiter
3772  protected function end()
3773  {
3774  if ($this->literal(';', false)) {
3775  return true;
3776  } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
3777  // if there is end of file or a closing block next then we don't need a ;
3778  return true;
3779  }
3780  return false;
3781  }
3782 
3783  protected function guards(&$guards)
3784  {
3785  $s = $this->seek();
3786 
3787  if (!$this->literal("when")) {
3788  $this->seek($s);
3789  return false;
3790  }
3791 
3792  $guards = array();
3793 
3794  while ($this->guardGroup($g)) {
3795  $guards[] = $g;
3796  if (!$this->literal(",")) {
3797  break;
3798  }
3799  }
3800 
3801  if (count($guards) == 0) {
3802  $guards = null;
3803  $this->seek($s);
3804  return false;
3805  }
3806 
3807  return true;
3808  }
3809 
3810  // a bunch of guards that are and'd together
3811  // TODO rename to guardGroup
3812  protected function guardGroup(&$guardGroup)
3813  {
3814  $s = $this->seek();
3815  $guardGroup = array();
3816  while ($this->guard($guard)) {
3817  $guardGroup[] = $guard;
3818  if (!$this->literal("and")) {
3819  break;
3820  }
3821  }
3822 
3823  if (count($guardGroup) == 0) {
3824  $guardGroup = null;
3825  $this->seek($s);
3826  return false;
3827  }
3828 
3829  return true;
3830  }
3831 
3832  protected function guard(&$guard)
3833  {
3834  $s = $this->seek();
3835  $negate = $this->literal("not");
3836 
3837  if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
3838  $guard = $exp;
3839  if ($negate) {
3840  $guard = array("negate", $guard);
3841  }
3842  return true;
3843  }
3844 
3845  $this->seek($s);
3846  return false;
3847  }
3848 
3849  /* raw parsing functions */
3850 
3851  protected function literal($what, $eatWhitespace = null)
3852  {
3853  if ($eatWhitespace === null) {
3854  $eatWhitespace = $this->eatWhiteDefault;
3855  }
3856 
3857  // shortcut on single letter
3858  if (!isset($what[1]) && isset($this->buffer[$this->count])) {
3859  if ($this->buffer[$this->count] == $what) {
3860  if (!$eatWhitespace) {
3861  $this->count++;
3862  return true;
3863  }
3864  // goes below...
3865  } else {
3866  return false;
3867  }
3868  }
3869 
3870  if (!isset(self::$literalCache[$what])) {
3871  self::$literalCache[$what] = lessc::preg_quote($what);
3872  }
3873 
3874  return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
3875  }
3876 
3877  protected function genericList(&$out, $parseItem, $delim = "", $flatten = true)
3878  {
3879  $s = $this->seek();
3880  $items = array();
3881  while ($this->$parseItem($value)) {
3882  $items[] = $value;
3883  if ($delim) {
3884  if (!$this->literal($delim)) {
3885  break;
3886  }
3887  }
3888  }
3889 
3890  if (count($items) == 0) {
3891  $this->seek($s);
3892  return false;
3893  }
3894 
3895  if ($flatten && count($items) == 1) {
3896  $out = $items[0];
3897  } else {
3898  $out = array("list", $delim, $items);
3899  }
3900 
3901  return true;
3902  }
3903 
3904 
3905  // advance counter to next occurrence of $what
3906  // $until - don't include $what in advance
3907  // $allowNewline, if string, will be used as valid char set
3908  protected function to($what, &$out, $until = false, $allowNewline = false)
3909  {
3910  if (is_string($allowNewline)) {
3911  $validChars = $allowNewline;
3912  } else {
3913  $validChars = $allowNewline ? "." : "[^\n]";
3914  }
3915  if (!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what), $m, !$until)) {
3916  return false;
3917  }
3918  if ($until) {
3919  $this->count -= strlen($what); // give back $what
3920  }
3921  $out = $m[1];
3922  return true;
3923  }
3924 
3925  // try to match something on head of buffer
3926  protected function match($regex, &$out, $eatWhitespace = null)
3927  {
3928  if ($eatWhitespace === null) {
3929  $eatWhitespace = $this->eatWhiteDefault;
3930  }
3931 
3932  $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
3933  if (preg_match($r, $this->buffer, $out, null, $this->count)) {
3934  $this->count += strlen($out[0]);
3935  if ($eatWhitespace && $this->writeComments) {
3936  $this->whitespace();
3937  }
3938  return true;
3939  }
3940  return false;
3941  }
3942 
3943  // match some whitespace
3944  protected function whitespace()
3945  {
3946  if ($this->writeComments) {
3947  $gotWhite = false;
3948  while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
3949  if (isset($m[1]) && empty($this->seenComments[$this->count])) {
3950  $this->append(array("comment", $m[1]));
3951  $this->seenComments[$this->count] = true;
3952  }
3953  $this->count += strlen($m[0]);
3954  $gotWhite = true;
3955  }
3956  return $gotWhite;
3957  } else {
3958  $this->match("", $m);
3959  return strlen($m[0]) > 0;
3960  }
3961  }
3962 
3963  // match something without consuming it
3964  protected function peek($regex, &$out = null, $from = null)
3965  {
3966  if (is_null($from)) {
3967  $from = $this->count;
3968  }
3969  $r = '/'.$regex.'/Ais';
3970  $result = preg_match($r, $this->buffer, $out, null, $from);
3971 
3972  return $result;
3973  }
3974 
3975  // seek to a spot in the buffer or return where we are on no argument
3976  protected function seek($where = null)
3977  {
3978  if ($where === null) {
3979  return $this->count;
3980  } else {
3981  $this->count = $where;
3982  }
3983  return true;
3984  }
3985 
3986  /* misc functions */
3987 
3988  public function throwError($msg = "parse error", $count = null)
3989  {
3990  $count = is_null($count) ? $this->count : $count;
3991 
3992  $line = $this->line +
3993  substr_count(substr($this->buffer, 0, $count), "\n");
3994 
3995  if (!empty($this->sourceName)) {
3996  $loc = "$this->sourceName on line $line";
3997  } else {
3998  $loc = "line: $line";
3999  }
4000 
4001  // TODO this depends on $this->count
4002  if ($this->peek("(.*?)(\n|$)", $m, $count)) {
4003  throw new exception("$msg: failed at `$m[1]` $loc");
4004  } else {
4005  throw new exception("$msg: $loc");
4006  }
4007  }
4008 
4009  protected function pushBlock($selectors = null, $type = null)
4010  {
4011  $b = new stdclass;
4012  $b->parent = $this->env;
4013 
4014  $b->type = $type;
4015  $b->id = self::$nextBlockId++;
4016 
4017  $b->isVararg = false; // TODO: kill me from here
4018  $b->tags = $selectors;
4019 
4020  $b->props = array();
4021  $b->children = array();
4022 
4023  $this->env = $b;
4024  return $b;
4025  }
4026 
4027  // push a block that doesn't multiply tags
4028  protected function pushSpecialBlock($type)
4029  {
4030  return $this->pushBlock(null, $type);
4031  }
4032 
4033  // append a property to the current block
4034  protected function append($prop, $pos = null)
4035  {
4036  if ($pos !== null) {
4037  $prop[-1] = $pos;
4038  }
4039  $this->env->props[] = $prop;
4040  }
4041 
4042  // pop something off the stack
4043  protected function pop()
4044  {
4045  $old = $this->env;
4046  $this->env = $this->env->parent;
4047  return $old;
4048  }
4049 
4050  // remove comments from $text
4051  // todo: make it work for all functions, not just url
4052  protected function removeComments($text)
4053  {
4054  $look = array(
4055  'url(', '//', '/*', '"', "'"
4056  );
4057 
4058  $out = '';
4059  $min = null;
4060  while (true) {
4061  // find the next item
4062  foreach ($look as $token) {
4063  $pos = strpos($text, $token);
4064  if ($pos !== false) {
4065  if (!isset($min) || $pos < $min[1]) {
4066  $min = array($token, $pos);
4067  }
4068  }
4069  }
4070 
4071  if (is_null($min)) {
4072  break;
4073  }
4074 
4075  $count = $min[1];
4076  $skip = 0;
4077  $newlines = 0;
4078  switch ($min[0]) {
4079  case 'url(':
4080  if (preg_match('/url\(.*?\)/', $text, $m, 0, $count)) {
4081  $count += strlen($m[0]) - strlen($min[0]);
4082  }
4083  break;
4084  case '"':
4085  case "'":
4086  if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count)) {
4087  $count += strlen($m[0]) - 1;
4088  }
4089  break;
4090  case '//':
4091  $skip = strpos($text, "\n", $count);
4092  if ($skip === false) {
4093  $skip = strlen($text) - $count;
4094  } else {
4095  $skip -= $count;
4096  }
4097  break;
4098  case '/*':
4099  if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
4100  $skip = strlen($m[0]);
4101  $newlines = substr_count($m[0], "\n");
4102  }
4103  break;
4104  }
4105 
4106  if ($skip == 0) {
4107  $count += strlen($min[0]);
4108  }
4109 
4110  $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
4111  $text = substr($text, $count + $skip);
4112 
4113  $min = null;
4114  }
4115 
4116  return $out.$text;
4117  }
4118 }
4119 
4121 {
4122  public $indentChar = " ";
4123 
4124  public $break = "\n";
4125  public $open = " {";
4126  public $close = "}";
4127  public $selectorSeparator = ", ";
4128  public $assignSeparator = ":";
4129 
4130  public $openSingle = " { ";
4131  public $closeSingle = " }";
4132 
4133  public $disableSingle = false;
4134  public $breakSelectors = false;
4135 
4136  public $compressColors = false;
4137 
4138  public function __construct()
4139  {
4140  $this->indentLevel = 0;
4141  }
4142 
4143  public function indentStr($n = 0)
4144  {
4145  return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
4146  }
4147 
4148  public function property($name, $value)
4149  {
4150  return $name.$this->assignSeparator.$value.";";
4151  }
4152 
4153  protected function isEmpty($block)
4154  {
4155  if (empty($block->lines)) {
4156  foreach ($block->children as $child) {
4157  if (!$this->isEmpty($child)) {
4158  return false;
4159  }
4160  }
4161 
4162  return true;
4163  }
4164  return false;
4165  }
4166 
4167  public function block($block)
4168  {
4169  if ($this->isEmpty($block)) {
4170  return;
4171  }
4172 
4173  $inner = $pre = $this->indentStr();
4174 
4175  $isSingle = !$this->disableSingle &&
4176  is_null($block->type) && count($block->lines) == 1;
4177 
4178  if (!empty($block->selectors)) {
4179  $this->indentLevel++;
4180 
4181  if ($this->breakSelectors) {
4182  $selectorSeparator = $this->selectorSeparator.$this->break.$pre;
4183  } else {
4184  $selectorSeparator = $this->selectorSeparator;
4185  }
4186 
4187  echo $pre.
4188  implode($selectorSeparator, $block->selectors);
4189  if ($isSingle) {
4190  echo $this->openSingle;
4191  $inner = "";
4192  } else {
4193  echo $this->open.$this->break;
4194  $inner = $this->indentStr();
4195  }
4196  }
4197 
4198  if (!empty($block->lines)) {
4199  $glue = $this->break.$inner;
4200  echo $inner.implode($glue, $block->lines);
4201  if (!$isSingle && !empty($block->children)) {
4202  echo $this->break;
4203  }
4204  }
4205 
4206  foreach ($block->children as $child) {
4207  $this->block($child);
4208  }
4209 
4210  if (!empty($block->selectors)) {
4211  if (!$isSingle && empty($block->children)) {
4212  echo $this->break;
4213  }
4214 
4215  if ($isSingle) {
4216  echo $this->closeSingle.$this->break;
4217  } else {
4218  echo $pre.$this->close.$this->break;
4219  }
4220 
4221  $this->indentLevel--;
4222  }
4223  }
4224 }
4225 
4230 {
4231  public $disableSingle = true;
4232  public $open = "{";
4233  public $selectorSeparator = ",";
4234  public $assignSeparator = ":";
4235  public $break = "";
4236  public $compressColors = true;
4237 
4238  public function indentStr($n = 0)
4239  {
4240  return "";
4241  }
4242 }
4243 
4248 {
4249  public $disableSingle = true;
4250  public $breakSelectors = true;
4251  public $assignSeparator = ": ";
4252  public $selectorSeparator = ",";
4253 }
Lessc\deduplicate
deduplicate($lines)
Deduplicate lines in a block.
Definition: lessc.class.php:321
Lessc\funcToColor
funcToColor($func)
Convert the rgb, rgba, hsl color literals of function type as returned by the parser into values of c...
Definition: lessc.class.php:1615
Lessc\compileValue
compileValue($value)
Compiles a primitive value into a CSS property value.
Definition: lessc.class.php:886
lessc_parser\expression
expression(&$out)
Attempt to consume an expression.
Definition: lessc.class.php:2936
lessc_parser\parseChunk
parseChunk()
Parse a single chunk off the head of the buffer and append it to the current parse environment.
Definition: lessc.class.php:2731
Lessc
lessphp v0.5.0 http://leafo.net/lessphp
Definition: lessc.class.php:38
Lessc\compileBlock
compileBlock($block)
Recursively compiles a block.
Definition: lessc.class.php:210
lessc_parser\$inParens
$inParens
if we are in parens we can be more liberal with whitespace around operators because it must evaluate ...
Definition: lessc.class.php:2624
lessc_parser\assign
assign($name=null)
Consume an assignment operator Can optionally take a name that will be set to the current property na...
Definition: lessc.class.php:3753
Lessc\toRGB
toRGB($color)
Converts a hsl array into a color value in rgb.
Definition: lessc.class.php:1574
Exception
Lessc\colorArgs
colorArgs($args)
Helper function to get arguments for color manipulation functions.
Definition: lessc.class.php:1208
lessc_formatter_compressed
Class for compressed result.
Definition: lessc.class.php:4229
lessc_parser\expHelper
expHelper($lhs, $minP)
recursively parse infix equation with $lhs at precedence $minP
Definition: lessc.class.php:2961
Lessc\throwError
throwError($msg=null)
Uses the current value of $this->count to show line and line number.
Definition: lessc.class.php:2400
lessc_parser\parse
parse($buffer)
Parse a string.
Definition: lessc.class.php:2662
Lessc\__construct
__construct($fname=null)
Initialize any static state, can initialize parser for a file $opts isn't used yet.
Definition: lessc.class.php:2162
Lessc\fileExists
fileExists($name)
fileExists
Definition: lessc.class.php:86
Lessc\cachedCompile
cachedCompile($in, $force=false)
Execute lessphp on a .less file or a lessphp cache structure.
Definition: lessc.class.php:2253
lessc_formatter_lessjs
Class for lessjs.
Definition: lessc.class.php:4247
lessc_parser
Definition: lessc.class.php:2580
Lessc\lib_data_uri
lib_data_uri($value)
Given an url, decide whether to output a regular link or the base64-encoded contents of the file.
Definition: lessc.class.php:1083
Lessc\lib_tint
lib_tint($args)
Mix color with white in variable proportion.
Definition: lessc.class.php:1336
Lessc\lib_shade
lib_shade($args)
Mix color with black in variable proportion.
Definition: lessc.class.php:1359
lessc_formatter_classic
Definition: lessc.class.php:4120