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