PageRenderTime 66ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/woocommerce/includes/libraries/class-lessc.php

https://bitbucket.org/theshipswakecreative/psw
PHP | 3767 lines | 2843 code | 579 blank | 345 comment | 657 complexity | f364e7a42a65e886a87f9b923bda1484 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * lessphp v0.4.0
  4. * http://leafo.net/lessphp
  5. *
  6. * LESS CSS compiler, adapted from http://lesscss.org
  7. *
  8. * Copyright 2013, Leaf Corcoran <leafot@gmail.com>
  9. * Licensed under MIT or GPLv3, see LICENSE
  10. */
  11. /**
  12. * The LESS compiler and parser.
  13. *
  14. * Converting LESS to CSS is a three stage process. The incoming file is parsed
  15. * by `lessc_parser` into a syntax tree, then it is compiled into another tree
  16. * representing the CSS structure by `lessc`. The CSS tree is fed into a
  17. * formatter, like `lessc_formatter` which then outputs CSS as a string.
  18. *
  19. * During the first compile, all values are *reduced*, which means that their
  20. * types are brought to the lowest form before being dump as strings. This
  21. * handles math equations, variable dereferences, and the like.
  22. *
  23. * The `parse` function of `lessc` is the entry point.
  24. *
  25. * In summary:
  26. *
  27. * The `lessc` class creates an instance of the parser, feeds it LESS code,
  28. * then transforms the resulting tree to a CSS tree. This class also holds the
  29. * evaluation context, such as all available mixins and variables at any given
  30. * time.
  31. *
  32. * The `lessc_parser` class is only concerned with parsing its input.
  33. *
  34. * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
  35. * handling things like indentation.
  36. */
  37. class lessc {
  38. static public $VERSION = "v0.4.0";
  39. static public $TRUE = array("keyword", "true");
  40. static public $FALSE = array("keyword", "false");
  41. protected $libFunctions = array();
  42. protected $registeredVars = array();
  43. protected $preserveComments = false;
  44. public $vPrefix = '@'; // prefix of abstract properties
  45. public $mPrefix = '$'; // prefix of abstract blocks
  46. public $parentSelector = '&';
  47. public $importDisabled = false;
  48. public $importDir = '';
  49. protected $numberPrecision = null;
  50. protected $allParsedFiles = array();
  51. // set to the parser that generated the current line when compiling
  52. // so we know how to create error messages
  53. protected $sourceParser = null;
  54. protected $sourceLoc = null;
  55. static protected $nextImportId = 0; // uniquely identify imports
  56. // attempts to find the path of an import url, returns null for css files
  57. protected function findImport($url) {
  58. foreach ((array)$this->importDir as $dir) {
  59. $full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
  60. if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
  61. return $file;
  62. }
  63. }
  64. return null;
  65. }
  66. protected function fileExists($name) {
  67. return is_file($name);
  68. }
  69. static public function compressList($items, $delim) {
  70. if (!isset($items[1]) && isset($items[0])) return $items[0];
  71. else return array('list', $delim, $items);
  72. }
  73. static public function preg_quote($what) {
  74. return preg_quote($what, '/');
  75. }
  76. protected function tryImport($importPath, $parentBlock, $out) {
  77. if ($importPath[0] == "function" && $importPath[1] == "url") {
  78. $importPath = $this->flattenList($importPath[2]);
  79. }
  80. $str = $this->coerceString($importPath);
  81. if ($str === null) return false;
  82. $url = $this->compileValue($this->lib_e($str));
  83. // don't import if it ends in css
  84. if (substr_compare($url, '.css', -4, 4) === 0) return false;
  85. $realPath = $this->findImport($url);
  86. if ($realPath === null) return false;
  87. if ($this->importDisabled) {
  88. return array(false, "/* import disabled */");
  89. }
  90. if (isset($this->allParsedFiles[realpath($realPath)])) {
  91. return array(false, null);
  92. }
  93. $this->addParsedFile($realPath);
  94. $parser = $this->makeParser($realPath);
  95. $root = $parser->parse(file_get_contents($realPath));
  96. // set the parents of all the block props
  97. foreach ($root->props as $prop) {
  98. if ($prop[0] == "block") {
  99. $prop[1]->parent = $parentBlock;
  100. }
  101. }
  102. // copy mixins into scope, set their parents
  103. // bring blocks from import into current block
  104. // TODO: need to mark the source parser these came from this file
  105. foreach ($root->children as $childName => $child) {
  106. if (isset($parentBlock->children[$childName])) {
  107. $parentBlock->children[$childName] = array_merge(
  108. $parentBlock->children[$childName],
  109. $child);
  110. } else {
  111. $parentBlock->children[$childName] = $child;
  112. }
  113. }
  114. $pi = pathinfo($realPath);
  115. $dir = $pi["dirname"];
  116. list($top, $bottom) = $this->sortProps($root->props, true);
  117. $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
  118. return array(true, $bottom, $parser, $dir);
  119. }
  120. protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
  121. $oldSourceParser = $this->sourceParser;
  122. $oldImport = $this->importDir;
  123. // TODO: this is because the importDir api is stupid
  124. $this->importDir = (array)$this->importDir;
  125. array_unshift($this->importDir, $importDir);
  126. foreach ($props as $prop) {
  127. $this->compileProp($prop, $block, $out);
  128. }
  129. $this->importDir = $oldImport;
  130. $this->sourceParser = $oldSourceParser;
  131. }
  132. /**
  133. * Recursively compiles a block.
  134. *
  135. * A block is analogous to a CSS block in most cases. A single LESS document
  136. * is encapsulated in a block when parsed, but it does not have parent tags
  137. * so all of it's children appear on the root level when compiled.
  138. *
  139. * Blocks are made up of props and children.
  140. *
  141. * Props are property instructions, array tuples which describe an action
  142. * to be taken, eg. write a property, set a variable, mixin a block.
  143. *
  144. * The children of a block are just all the blocks that are defined within.
  145. * This is used to look up mixins when performing a mixin.
  146. *
  147. * Compiling the block involves pushing a fresh environment on the stack,
  148. * and iterating through the props, compiling each one.
  149. *
  150. * See lessc::compileProp()
  151. *
  152. */
  153. protected function compileBlock($block) {
  154. switch ($block->type) {
  155. case "root":
  156. $this->compileRoot($block);
  157. break;
  158. case null:
  159. $this->compileCSSBlock($block);
  160. break;
  161. case "media":
  162. $this->compileMedia($block);
  163. break;
  164. case "directive":
  165. $name = "@" . $block->name;
  166. if (!empty($block->value)) {
  167. $name .= " " . $this->compileValue($this->reduce($block->value));
  168. }
  169. $this->compileNestedBlock($block, array($name));
  170. break;
  171. default:
  172. $this->throwError("unknown block type: $block->type\n");
  173. }
  174. }
  175. protected function compileCSSBlock($block) {
  176. $env = $this->pushEnv();
  177. $selectors = $this->compileSelectors($block->tags);
  178. $env->selectors = $this->multiplySelectors($selectors);
  179. $out = $this->makeOutputBlock(null, $env->selectors);
  180. $this->scope->children[] = $out;
  181. $this->compileProps($block, $out);
  182. $block->scope = $env; // mixins carry scope with them!
  183. $this->popEnv();
  184. }
  185. protected function compileMedia($media) {
  186. $env = $this->pushEnv($media);
  187. $parentScope = $this->mediaParent($this->scope);
  188. $query = $this->compileMediaQuery($this->multiplyMedia($env));
  189. $this->scope = $this->makeOutputBlock($media->type, array($query));
  190. $parentScope->children[] = $this->scope;
  191. $this->compileProps($media, $this->scope);
  192. if (count($this->scope->lines) > 0) {
  193. $orphanSelelectors = $this->findClosestSelectors();
  194. if (!is_null($orphanSelelectors)) {
  195. $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
  196. $orphan->lines = $this->scope->lines;
  197. array_unshift($this->scope->children, $orphan);
  198. $this->scope->lines = array();
  199. }
  200. }
  201. $this->scope = $this->scope->parent;
  202. $this->popEnv();
  203. }
  204. protected function mediaParent($scope) {
  205. while (!empty($scope->parent)) {
  206. if (!empty($scope->type) && $scope->type != "media") {
  207. break;
  208. }
  209. $scope = $scope->parent;
  210. }
  211. return $scope;
  212. }
  213. protected function compileNestedBlock($block, $selectors) {
  214. $this->pushEnv($block);
  215. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  216. $this->scope->parent->children[] = $this->scope;
  217. $this->compileProps($block, $this->scope);
  218. $this->scope = $this->scope->parent;
  219. $this->popEnv();
  220. }
  221. protected function compileRoot($root) {
  222. $this->pushEnv();
  223. $this->scope = $this->makeOutputBlock($root->type);
  224. $this->compileProps($root, $this->scope);
  225. $this->popEnv();
  226. }
  227. protected function compileProps($block, $out) {
  228. foreach ($this->sortProps($block->props) as $prop) {
  229. $this->compileProp($prop, $block, $out);
  230. }
  231. $out->lines = $this->deduplicate($out->lines);
  232. }
  233. /**
  234. * Deduplicate lines in a block. Comments are not deduplicated. If a
  235. * duplicate rule is detected, the comments immediately preceding each
  236. * occurence are consolidated.
  237. */
  238. protected function deduplicate($lines) {
  239. $unique = array();
  240. $comments = array();
  241. foreach($lines as $line) {
  242. if (strpos($line, '/*') === 0) {
  243. $comments[] = $line;
  244. continue;
  245. }
  246. if (!in_array($line, $unique)) {
  247. $unique[] = $line;
  248. }
  249. array_splice($unique, array_search($line, $unique), 0, $comments);
  250. $comments = array();
  251. }
  252. return array_merge($unique, $comments);
  253. }
  254. protected function sortProps($props, $split = false) {
  255. $vars = array();
  256. $imports = array();
  257. $other = array();
  258. $stack = array();
  259. foreach ($props as $prop) {
  260. switch ($prop[0]) {
  261. case "comment":
  262. $stack[] = $prop;
  263. break;
  264. case "assign":
  265. $stack[] = $prop;
  266. if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) {
  267. $vars = array_merge($vars, $stack);
  268. } else {
  269. $other = array_merge($other, $stack);
  270. }
  271. $stack = array();
  272. break;
  273. case "import":
  274. $id = self::$nextImportId++;
  275. $prop[] = $id;
  276. $stack[] = $prop;
  277. $imports = array_merge($imports, $stack);
  278. $other[] = array("import_mixin", $id);
  279. $stack = array();
  280. break;
  281. default:
  282. $stack[] = $prop;
  283. $other = array_merge($other, $stack);
  284. $stack = array();
  285. break;
  286. }
  287. }
  288. $other = array_merge($other, $stack);
  289. if ($split) {
  290. return array(array_merge($vars, $imports), $other);
  291. } else {
  292. return array_merge($vars, $imports, $other);
  293. }
  294. }
  295. protected function compileMediaQuery($queries) {
  296. $compiledQueries = array();
  297. foreach ($queries as $query) {
  298. $parts = array();
  299. foreach ($query as $q) {
  300. switch ($q[0]) {
  301. case "mediaType":
  302. $parts[] = implode(" ", array_slice($q, 1));
  303. break;
  304. case "mediaExp":
  305. if (isset($q[2])) {
  306. $parts[] = "($q[1]: " .
  307. $this->compileValue($this->reduce($q[2])) . ")";
  308. } else {
  309. $parts[] = "($q[1])";
  310. }
  311. break;
  312. case "variable":
  313. $parts[] = $this->compileValue($this->reduce($q));
  314. break;
  315. }
  316. }
  317. if (count($parts) > 0) {
  318. $compiledQueries[] = implode(" and ", $parts);
  319. }
  320. }
  321. $out = "@media";
  322. if (!empty($parts)) {
  323. $out .= " " .
  324. implode($this->formatter->selectorSeparator, $compiledQueries);
  325. }
  326. return $out;
  327. }
  328. protected function multiplyMedia($env, $childQueries = null) {
  329. if (is_null($env) ||
  330. !empty($env->block->type) && $env->block->type != "media")
  331. {
  332. return $childQueries;
  333. }
  334. // plain old block, skip
  335. if (empty($env->block->type)) {
  336. return $this->multiplyMedia($env->parent, $childQueries);
  337. }
  338. $out = array();
  339. $queries = $env->block->queries;
  340. if (is_null($childQueries)) {
  341. $out = $queries;
  342. } else {
  343. foreach ($queries as $parent) {
  344. foreach ($childQueries as $child) {
  345. $out[] = array_merge($parent, $child);
  346. }
  347. }
  348. }
  349. return $this->multiplyMedia($env->parent, $out);
  350. }
  351. protected function expandParentSelectors(&$tag, $replace) {
  352. $parts = explode("$&$", $tag);
  353. $count = 0;
  354. foreach ($parts as &$part) {
  355. $part = str_replace($this->parentSelector, $replace, $part, $c);
  356. $count += $c;
  357. }
  358. $tag = implode($this->parentSelector, $parts);
  359. return $count;
  360. }
  361. protected function findClosestSelectors() {
  362. $env = $this->env;
  363. $selectors = null;
  364. while ($env !== null) {
  365. if (isset($env->selectors)) {
  366. $selectors = $env->selectors;
  367. break;
  368. }
  369. $env = $env->parent;
  370. }
  371. return $selectors;
  372. }
  373. // multiply $selectors against the nearest selectors in env
  374. protected function multiplySelectors($selectors) {
  375. // find parent selectors
  376. $parentSelectors = $this->findClosestSelectors();
  377. if (is_null($parentSelectors)) {
  378. // kill parent reference in top level selector
  379. foreach ($selectors as &$s) {
  380. $this->expandParentSelectors($s, "");
  381. }
  382. return $selectors;
  383. }
  384. $out = array();
  385. foreach ($parentSelectors as $parent) {
  386. foreach ($selectors as $child) {
  387. $count = $this->expandParentSelectors($child, $parent);
  388. // don't prepend the parent tag if & was used
  389. if ($count > 0) {
  390. $out[] = trim($child);
  391. } else {
  392. $out[] = trim($parent . ' ' . $child);
  393. }
  394. }
  395. }
  396. return $out;
  397. }
  398. // reduces selector expressions
  399. protected function compileSelectors($selectors) {
  400. $out = array();
  401. foreach ($selectors as $s) {
  402. if (is_array($s)) {
  403. list(, $value) = $s;
  404. $out[] = trim($this->compileValue($this->reduce($value)));
  405. } else {
  406. $out[] = $s;
  407. }
  408. }
  409. return $out;
  410. }
  411. protected function eq($left, $right) {
  412. return $left == $right;
  413. }
  414. protected function patternMatch($block, $orderedArgs, $keywordArgs) {
  415. // match the guards if it has them
  416. // any one of the groups must have all its guards pass for a match
  417. if (!empty($block->guards)) {
  418. $groupPassed = false;
  419. foreach ($block->guards as $guardGroup) {
  420. foreach ($guardGroup as $guard) {
  421. $this->pushEnv();
  422. $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
  423. $negate = false;
  424. if ($guard[0] == "negate") {
  425. $guard = $guard[1];
  426. $negate = true;
  427. }
  428. $passed = $this->reduce($guard) == self::$TRUE;
  429. if ($negate) $passed = !$passed;
  430. $this->popEnv();
  431. if ($passed) {
  432. $groupPassed = true;
  433. } else {
  434. $groupPassed = false;
  435. break;
  436. }
  437. }
  438. if ($groupPassed) break;
  439. }
  440. if (!$groupPassed) {
  441. return false;
  442. }
  443. }
  444. if (empty($block->args)) {
  445. return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
  446. }
  447. $remainingArgs = $block->args;
  448. if ($keywordArgs) {
  449. $remainingArgs = array();
  450. foreach ($block->args as $arg) {
  451. if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
  452. continue;
  453. }
  454. $remainingArgs[] = $arg;
  455. }
  456. }
  457. $i = -1; // no args
  458. // try to match by arity or by argument literal
  459. foreach ($remainingArgs as $i => $arg) {
  460. switch ($arg[0]) {
  461. case "lit":
  462. if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
  463. return false;
  464. }
  465. break;
  466. case "arg":
  467. // no arg and no default value
  468. if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
  469. return false;
  470. }
  471. break;
  472. case "rest":
  473. $i--; // rest can be empty
  474. break 2;
  475. }
  476. }
  477. if ($block->isVararg) {
  478. return true; // not having enough is handled above
  479. } else {
  480. $numMatched = $i + 1;
  481. // greater than becuase default values always match
  482. return $numMatched >= count($orderedArgs);
  483. }
  484. }
  485. protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) {
  486. $matches = null;
  487. foreach ($blocks as $block) {
  488. // skip seen blocks that don't have arguments
  489. if (isset($skip[$block->id]) && !isset($block->args)) {
  490. continue;
  491. }
  492. if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
  493. $matches[] = $block;
  494. }
  495. }
  496. return $matches;
  497. }
  498. // attempt to find blocks matched by path and args
  499. protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) {
  500. if ($searchIn == null) return null;
  501. if (isset($seen[$searchIn->id])) return null;
  502. $seen[$searchIn->id] = true;
  503. $name = $path[0];
  504. if (isset($searchIn->children[$name])) {
  505. $blocks = $searchIn->children[$name];
  506. if (count($path) == 1) {
  507. $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
  508. if (!empty($matches)) {
  509. // This will return all blocks that match in the closest
  510. // scope that has any matching block, like lessjs
  511. return $matches;
  512. }
  513. } else {
  514. $matches = array();
  515. foreach ($blocks as $subBlock) {
  516. $subMatches = $this->findBlocks($subBlock,
  517. array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
  518. if (!is_null($subMatches)) {
  519. foreach ($subMatches as $sm) {
  520. $matches[] = $sm;
  521. }
  522. }
  523. }
  524. return count($matches) > 0 ? $matches : null;
  525. }
  526. }
  527. if ($searchIn->parent === $searchIn) return null;
  528. return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
  529. }
  530. // sets all argument names in $args to either the default value
  531. // or the one passed in through $values
  532. protected function zipSetArgs($args, $orderedValues, $keywordValues) {
  533. $assignedValues = array();
  534. $i = 0;
  535. foreach ($args as $a) {
  536. if ($a[0] == "arg") {
  537. if (isset($keywordValues[$a[1]])) {
  538. // has keyword arg
  539. $value = $keywordValues[$a[1]];
  540. } elseif (isset($orderedValues[$i])) {
  541. // has ordered arg
  542. $value = $orderedValues[$i];
  543. $i++;
  544. } elseif (isset($a[2])) {
  545. // has default value
  546. $value = $a[2];
  547. } else {
  548. $this->throwError("Failed to assign arg " . $a[1]);
  549. $value = null; // :(
  550. }
  551. $value = $this->reduce($value);
  552. $this->set($a[1], $value);
  553. $assignedValues[] = $value;
  554. } else {
  555. // a lit
  556. $i++;
  557. }
  558. }
  559. // check for a rest
  560. $last = end($args);
  561. if ($last[0] == "rest") {
  562. $rest = array_slice($orderedValues, count($args) - 1);
  563. $this->set($last[1], $this->reduce(array("list", " ", $rest)));
  564. }
  565. // wow is this the only true use of PHP's + operator for arrays?
  566. $this->env->arguments = $assignedValues + $orderedValues;
  567. }
  568. // compile a prop and update $lines or $blocks appropriately
  569. protected function compileProp($prop, $block, $out) {
  570. // set error position context
  571. $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;
  572. switch ($prop[0]) {
  573. case 'assign':
  574. list(, $name, $value) = $prop;
  575. if ($name[0] == $this->vPrefix) {
  576. $this->set($name, $value);
  577. } else {
  578. $out->lines[] = $this->formatter->property($name,
  579. $this->compileValue($this->reduce($value)));
  580. }
  581. break;
  582. case 'block':
  583. list(, $child) = $prop;
  584. $this->compileBlock($child);
  585. break;
  586. case 'mixin':
  587. list(, $path, $args, $suffix) = $prop;
  588. $orderedArgs = array();
  589. $keywordArgs = array();
  590. foreach ((array)$args as $arg) {
  591. $argval = null;
  592. switch ($arg[0]) {
  593. case "arg":
  594. if (!isset($arg[2])) {
  595. $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
  596. } else {
  597. $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
  598. }
  599. break;
  600. case "lit":
  601. $orderedArgs[] = $this->reduce($arg[1]);
  602. break;
  603. default:
  604. $this->throwError("Unknown arg type: " . $arg[0]);
  605. }
  606. }
  607. $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
  608. if ($mixins === null) {
  609. $this->throwError("{$prop[1][0]} is undefined");
  610. }
  611. foreach ($mixins as $mixin) {
  612. if ($mixin === $block && !$orderedArgs) {
  613. continue;
  614. }
  615. $haveScope = false;
  616. if (isset($mixin->parent->scope)) {
  617. $haveScope = true;
  618. $mixinParentEnv = $this->pushEnv();
  619. $mixinParentEnv->storeParent = $mixin->parent->scope;
  620. }
  621. $haveArgs = false;
  622. if (isset($mixin->args)) {
  623. $haveArgs = true;
  624. $this->pushEnv();
  625. $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs);
  626. }
  627. $oldParent = $mixin->parent;
  628. if ($mixin != $block) $mixin->parent = $block;
  629. foreach ($this->sortProps($mixin->props) as $subProp) {
  630. if ($suffix !== null &&
  631. $subProp[0] == "assign" &&
  632. is_string($subProp[1]) &&
  633. $subProp[1]{0} != $this->vPrefix)
  634. {
  635. $subProp[2] = array(
  636. 'list', ' ',
  637. array($subProp[2], array('keyword', $suffix))
  638. );
  639. }
  640. $this->compileProp($subProp, $mixin, $out);
  641. }
  642. $mixin->parent = $oldParent;
  643. if ($haveArgs) $this->popEnv();
  644. if ($haveScope) $this->popEnv();
  645. }
  646. break;
  647. case 'raw':
  648. $out->lines[] = $prop[1];
  649. break;
  650. case "directive":
  651. list(, $name, $value) = $prop;
  652. $out->lines[] = "@$name " . $this->compileValue($this->reduce($value)).';';
  653. break;
  654. case "comment":
  655. $out->lines[] = $prop[1];
  656. break;
  657. case "import";
  658. list(, $importPath, $importId) = $prop;
  659. $importPath = $this->reduce($importPath);
  660. if (!isset($this->env->imports)) {
  661. $this->env->imports = array();
  662. }
  663. $result = $this->tryImport($importPath, $block, $out);
  664. $this->env->imports[$importId] = $result === false ?
  665. array(false, "@import " . $this->compileValue($importPath).";") :
  666. $result;
  667. break;
  668. case "import_mixin":
  669. list(,$importId) = $prop;
  670. $import = $this->env->imports[$importId];
  671. if ($import[0] === false) {
  672. if (isset($import[1])) {
  673. $out->lines[] = $import[1];
  674. }
  675. } else {
  676. list(, $bottom, $parser, $importDir) = $import;
  677. $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
  678. }
  679. break;
  680. default:
  681. $this->throwError("unknown op: {$prop[0]}\n");
  682. }
  683. }
  684. /**
  685. * Compiles a primitive value into a CSS property value.
  686. *
  687. * Values in lessphp are typed by being wrapped in arrays, their format is
  688. * typically:
  689. *
  690. * array(type, contents [, additional_contents]*)
  691. *
  692. * The input is expected to be reduced. This function will not work on
  693. * things like expressions and variables.
  694. */
  695. protected function compileValue($value) {
  696. switch ($value[0]) {
  697. case 'list':
  698. // [1] - delimiter
  699. // [2] - array of values
  700. return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
  701. case 'raw_color':
  702. if (!empty($this->formatter->compressColors)) {
  703. return $this->compileValue($this->coerceColor($value));
  704. }
  705. return $value[1];
  706. case 'keyword':
  707. // [1] - the keyword
  708. return $value[1];
  709. case 'number':
  710. list(, $num, $unit) = $value;
  711. // [1] - the number
  712. // [2] - the unit
  713. if ($this->numberPrecision !== null) {
  714. $num = round($num, $this->numberPrecision);
  715. }
  716. return $num . $unit;
  717. case 'string':
  718. // [1] - contents of string (includes quotes)
  719. list(, $delim, $content) = $value;
  720. foreach ($content as &$part) {
  721. if (is_array($part)) {
  722. $part = $this->compileValue($part);
  723. }
  724. }
  725. return $delim . implode($content) . $delim;
  726. case 'color':
  727. // [1] - red component (either number or a %)
  728. // [2] - green component
  729. // [3] - blue component
  730. // [4] - optional alpha component
  731. list(, $r, $g, $b) = $value;
  732. $r = round($r);
  733. $g = round($g);
  734. $b = round($b);
  735. if (count($value) == 5 && $value[4] != 1) { // rgba
  736. return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
  737. }
  738. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  739. if (!empty($this->formatter->compressColors)) {
  740. // Converting hex color to short notation (e.g. #003399 to #039)
  741. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  742. $h = '#' . $h[1] . $h[3] . $h[5];
  743. }
  744. }
  745. return $h;
  746. case 'function':
  747. list(, $name, $args) = $value;
  748. return $name.'('.$this->compileValue($args).')';
  749. default: // assumed to be unit
  750. $this->throwError("unknown value type: $value[0]");
  751. }
  752. }
  753. protected function lib_pow($args) {
  754. list($base, $exp) = $this->assertArgs($args, 2, "pow");
  755. return pow($this->assertNumber($base), $this->assertNumber($exp));
  756. }
  757. protected function lib_pi() {
  758. return pi();
  759. }
  760. protected function lib_mod($args) {
  761. list($a, $b) = $this->assertArgs($args, 2, "mod");
  762. return $this->assertNumber($a) % $this->assertNumber($b);
  763. }
  764. protected function lib_tan($num) {
  765. return tan($this->assertNumber($num));
  766. }
  767. protected function lib_sin($num) {
  768. return sin($this->assertNumber($num));
  769. }
  770. protected function lib_cos($num) {
  771. return cos($this->assertNumber($num));
  772. }
  773. protected function lib_atan($num) {
  774. $num = atan($this->assertNumber($num));
  775. return array("number", $num, "rad");
  776. }
  777. protected function lib_asin($num) {
  778. $num = asin($this->assertNumber($num));
  779. return array("number", $num, "rad");
  780. }
  781. protected function lib_acos($num) {
  782. $num = acos($this->assertNumber($num));
  783. return array("number", $num, "rad");
  784. }
  785. protected function lib_sqrt($num) {
  786. return sqrt($this->assertNumber($num));
  787. }
  788. protected function lib_extract($value) {
  789. list($list, $idx) = $this->assertArgs($value, 2, "extract");
  790. $idx = $this->assertNumber($idx);
  791. // 1 indexed
  792. if ($list[0] == "list" && isset($list[2][$idx - 1])) {
  793. return $list[2][$idx - 1];
  794. }
  795. }
  796. protected function lib_isnumber($value) {
  797. return $this->toBool($value[0] == "number");
  798. }
  799. protected function lib_isstring($value) {
  800. return $this->toBool($value[0] == "string");
  801. }
  802. protected function lib_iscolor($value) {
  803. return $this->toBool($this->coerceColor($value));
  804. }
  805. protected function lib_iskeyword($value) {
  806. return $this->toBool($value[0] == "keyword");
  807. }
  808. protected function lib_ispixel($value) {
  809. return $this->toBool($value[0] == "number" && $value[2] == "px");
  810. }
  811. protected function lib_ispercentage($value) {
  812. return $this->toBool($value[0] == "number" && $value[2] == "%");
  813. }
  814. protected function lib_isem($value) {
  815. return $this->toBool($value[0] == "number" && $value[2] == "em");
  816. }
  817. protected function lib_isrem($value) {
  818. return $this->toBool($value[0] == "number" && $value[2] == "rem");
  819. }
  820. protected function lib_rgbahex($color) {
  821. $color = $this->coerceColor($color);
  822. if (is_null($color))
  823. $this->throwError("color expected for rgbahex");
  824. return sprintf("#%02x%02x%02x%02x",
  825. isset($color[4]) ? $color[4]*255 : 255,
  826. $color[1],$color[2], $color[3]);
  827. }
  828. protected function lib_argb($color){
  829. return $this->lib_rgbahex($color);
  830. }
  831. /**
  832. * Given an url, decide whether to output a regular link or the base64-encoded contents of the file
  833. *
  834. * @param array $value either an argument list (two strings) or a single string
  835. * @return string formatted url(), either as a link or base64-encoded
  836. */
  837. protected function lib_data_uri($value) {
  838. $mime = ($value[0] === 'list') ? $value[2][0][2] : null;
  839. $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0];
  840. $fullpath = $this->findImport($url);
  841. if($fullpath && ($fsize = filesize($fullpath)) !== false) {
  842. // IE8 can't handle data uris larger than 32KB
  843. if($fsize/1024 < 32) {
  844. if(is_null($mime)) {
  845. if(class_exists('finfo')) { // php 5.3+
  846. $finfo = new finfo(FILEINFO_MIME);
  847. $mime = explode('; ', $finfo->file($fullpath));
  848. $mime = $mime[0];
  849. } elseif(function_exists('mime_content_type')) { // PHP 5.2
  850. $mime = mime_content_type($fullpath);
  851. }
  852. }
  853. if(!is_null($mime)) // fallback if the mime type is still unknown
  854. $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
  855. }
  856. }
  857. return 'url("'.$url.'")';
  858. }
  859. // utility func to unquote a string
  860. protected function lib_e($arg) {
  861. switch ($arg[0]) {
  862. case "list":
  863. $items = $arg[2];
  864. if (isset($items[0])) {
  865. return $this->lib_e($items[0]);
  866. }
  867. $this->throwError("unrecognised input");
  868. case "string":
  869. $arg[1] = "";
  870. return $arg;
  871. case "keyword":
  872. return $arg;
  873. default:
  874. return array("keyword", $this->compileValue($arg));
  875. }
  876. }
  877. protected function lib__sprintf($args) {
  878. if ($args[0] != "list") return $args;
  879. $values = $args[2];
  880. $string = array_shift($values);
  881. $template = $this->compileValue($this->lib_e($string));
  882. $i = 0;
  883. if (preg_match_all('/%[dsa]/', $template, $m)) {
  884. foreach ($m[0] as $match) {
  885. $val = isset($values[$i]) ?
  886. $this->reduce($values[$i]) : array('keyword', '');
  887. // lessjs compat, renders fully expanded color, not raw color
  888. if ($color = $this->coerceColor($val)) {
  889. $val = $color;
  890. }
  891. $i++;
  892. $rep = $this->compileValue($this->lib_e($val));
  893. $template = preg_replace('/'.self::preg_quote($match).'/',
  894. $rep, $template, 1);
  895. }
  896. }
  897. $d = $string[0] == "string" ? $string[1] : '"';
  898. return array("string", $d, array($template));
  899. }
  900. protected function lib_floor($arg) {
  901. $value = $this->assertNumber($arg);
  902. return array("number", floor($value), $arg[2]);
  903. }
  904. protected function lib_ceil($arg) {
  905. $value = $this->assertNumber($arg);
  906. return array("number", ceil($value), $arg[2]);
  907. }
  908. protected function lib_round($arg) {
  909. if($arg[0] != "list") {
  910. $value = $this->assertNumber($arg);
  911. return array("number", round($value), $arg[2]);
  912. } else {
  913. $value = $this->assertNumber($arg[2][0]);
  914. $precision = $this->assertNumber($arg[2][1]);
  915. return array("number", round($value, $precision), $arg[2][0][2]);
  916. }
  917. }
  918. protected function lib_unit($arg) {
  919. if ($arg[0] == "list") {
  920. list($number, $newUnit) = $arg[2];
  921. return array("number", $this->assertNumber($number),
  922. $this->compileValue($this->lib_e($newUnit)));
  923. } else {
  924. return array("number", $this->assertNumber($arg), "");
  925. }
  926. }
  927. /**
  928. * Helper function to get arguments for color manipulation functions.
  929. * takes a list that contains a color like thing and a percentage
  930. */
  931. public function colorArgs($args) {
  932. if ($args[0] != 'list' || count($args[2]) < 2) {
  933. return array(array('color', 0, 0, 0), 0);
  934. }
  935. list($color, $delta) = $args[2];
  936. $color = $this->assertColor($color);
  937. $delta = floatval($delta[1]);
  938. return array($color, $delta);
  939. }
  940. protected function lib_darken($args) {
  941. list($color, $delta) = $this->colorArgs($args);
  942. $hsl = $this->toHSL($color);
  943. $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
  944. return $this->toRGB($hsl);
  945. }
  946. protected function lib_lighten($args) {
  947. list($color, $delta) = $this->colorArgs($args);
  948. $hsl = $this->toHSL($color);
  949. $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
  950. return $this->toRGB($hsl);
  951. }
  952. protected function lib_saturate($args) {
  953. list($color, $delta) = $this->colorArgs($args);
  954. $hsl = $this->toHSL($color);
  955. $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
  956. return $this->toRGB($hsl);
  957. }
  958. protected function lib_desaturate($args) {
  959. list($color, $delta) = $this->colorArgs($args);
  960. $hsl = $this->toHSL($color);
  961. $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
  962. return $this->toRGB($hsl);
  963. }
  964. protected function lib_spin($args) {
  965. list($color, $delta) = $this->colorArgs($args);
  966. $hsl = $this->toHSL($color);
  967. $hsl[1] = $hsl[1] + $delta % 360;
  968. if ($hsl[1] < 0) $hsl[1] += 360;
  969. return $this->toRGB($hsl);
  970. }
  971. protected function lib_fadeout($args) {
  972. list($color, $delta) = $this->colorArgs($args);
  973. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta/100);
  974. return $color;
  975. }
  976. protected function lib_fadein($args) {
  977. list($color, $delta) = $this->colorArgs($args);
  978. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta/100);
  979. return $color;
  980. }
  981. protected function lib_hue($color) {
  982. $hsl = $this->toHSL($this->assertColor($color));
  983. return round($hsl[1]);
  984. }
  985. protected function lib_saturation($color) {
  986. $hsl = $this->toHSL($this->assertColor($color));
  987. return round($hsl[2]);
  988. }
  989. protected function lib_lightness($color) {
  990. $hsl = $this->toHSL($this->assertColor($color));
  991. return round($hsl[3]);
  992. }
  993. // get the alpha of a color
  994. // defaults to 1 for non-colors or colors without an alpha
  995. protected function lib_alpha($value) {
  996. if (!is_null($color = $this->coerceColor($value))) {
  997. return isset($color[4]) ? $color[4] : 1;
  998. }
  999. }
  1000. // set the alpha of the color
  1001. protected function lib_fade($args) {
  1002. list($color, $alpha) = $this->colorArgs($args);
  1003. $color[4] = $this->clamp($alpha / 100.0);
  1004. return $color;
  1005. }
  1006. protected function lib_percentage($arg) {
  1007. $num = $this->assertNumber($arg);
  1008. return array("number", $num*100, "%");
  1009. }
  1010. // mixes two colors by weight
  1011. // mix(@color1, @color2, [@weight: 50%]);
  1012. // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
  1013. protected function lib_mix($args) {
  1014. if ($args[0] != "list" || count($args[2]) < 2)
  1015. $this->throwError("mix expects (color1, color2, weight)");
  1016. list($first, $second) = $args[2];
  1017. $first = $this->assertColor($first);
  1018. $second = $this->assertColor($second);
  1019. $first_a = $this->lib_alpha($first);
  1020. $second_a = $this->lib_alpha($second);
  1021. if (isset($args[2][2])) {
  1022. $weight = $args[2][2][1] / 100.0;
  1023. } else {
  1024. $weight = 0.5;
  1025. }
  1026. $w = $weight * 2 - 1;
  1027. $a = $first_a - $second_a;
  1028. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  1029. $w2 = 1.0 - $w1;
  1030. $new = array('color',
  1031. $w1 * $first[1] + $w2 * $second[1],
  1032. $w1 * $first[2] + $w2 * $second[2],
  1033. $w1 * $first[3] + $w2 * $second[3],
  1034. );
  1035. if ($first_a != 1.0 || $second_a != 1.0) {
  1036. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  1037. }
  1038. return $this->fixColor($new);
  1039. }
  1040. protected function lib_contrast($args) {
  1041. $darkColor = array('color', 0, 0, 0);
  1042. $lightColor = array('color', 255, 255, 255);
  1043. $threshold = 0.43;
  1044. if ( $args[0] == 'list' ) {
  1045. $inputColor = ( isset($args[2][0]) ) ? $this->assertColor($args[2][0]) : $lightColor;
  1046. $darkColor = ( isset($args[2][1]) ) ? $this->assertColor($args[2][1]) : $darkColor;
  1047. $lightColor = ( isset($args[2][2]) ) ? $this->assertColor($args[2][2]) : $lightColor;
  1048. $threshold = ( isset($args[2][3]) ) ? $this->assertNumber($args[2][3]) : $threshold;
  1049. }
  1050. else {
  1051. $inputColor = $this->assertColor($args);
  1052. }
  1053. $inputColor = $this->coerceColor($inputColor);
  1054. $darkColor = $this->coerceColor($darkColor);
  1055. $lightColor = $this->coerceColor($lightColor);
  1056. //Figure out which is actually light and dark!
  1057. if ( $this->lib_luma($darkColor) > $this->lib_luma($lightColor) ) {
  1058. $t = $lightColor;
  1059. $lightColor = $darkColor;
  1060. $darkColor = $t;
  1061. }
  1062. $inputColor_alpha = $this->lib_alpha($inputColor);
  1063. if ( ( $this->lib_luma($inputColor) * $inputColor_alpha) < $threshold) {
  1064. return $lightColor;
  1065. }
  1066. return $darkColor;
  1067. }
  1068. protected function lib_luma($color) {
  1069. $color = $this->coerceColor($color);
  1070. return (0.2126 * $color[0] / 255) + (0.7152 * $color[1] / 255) + (0.0722 * $color[2] / 255);
  1071. }
  1072. public function assertColor($value, $error = "expected color value") {
  1073. $color = $this->coerceColor($value);
  1074. if (is_null($color)) $this->throwError($error);
  1075. return $color;
  1076. }
  1077. public function assertNumber($value, $error = "expecting number") {
  1078. if ($value[0] == "number") return $value[1];
  1079. $this->throwError($error);
  1080. }
  1081. public function assertArgs($value, $expectedArgs, $name="") {
  1082. if ($expectedArgs == 1) {
  1083. return $value;
  1084. } else {
  1085. if ($value[0] !== "list" || $value[1] != ",") $this->throwError("expecting list");
  1086. $values = $value[2];
  1087. $numValues = count($values);
  1088. if ($expectedArgs != $numValues) {
  1089. if ($name) {
  1090. $name = $name . ": ";
  1091. }
  1092. $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
  1093. }
  1094. return $values;
  1095. }
  1096. }
  1097. protected function toHSL($color) {
  1098. if ($color[0] == 'hsl') return $color;
  1099. $r = $color[1] / 255;
  1100. $g = $color[2] / 255;
  1101. $b = $color[3] / 255;
  1102. $min = min($r, $g, $b);
  1103. $max = max($r, $g, $b);
  1104. $L = ($min + $max) / 2;
  1105. if ($min == $max) {
  1106. $S = $H = 0;
  1107. } else {
  1108. if ($L < 0.5)
  1109. $S = ($max - $min)/($max + $min);
  1110. else
  1111. $S = ($max - $min)/(2.0 - $max - $min);
  1112. if ($r == $max) $H = ($g - $b)/($max - $min);
  1113. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  1114. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  1115. }
  1116. $out = array('hsl',
  1117. ($H < 0 ? $H + 6 : $H)*60,
  1118. $S*100,
  1119. $L*100,
  1120. );
  1121. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  1122. return $out;
  1123. }
  1124. protected function toRGB_helper($comp, $temp1, $temp2) {
  1125. if ($comp < 0) $comp += 1.0;
  1126. elseif ($comp > 1) $comp -= 1.0;
  1127. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  1128. if (2 * $comp < 1) return $temp2;
  1129. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  1130. return $temp1;
  1131. }
  1132. /**
  1133. * Converts a hsl array into a color value in rgb.
  1134. * Expects H to be in range of 0 to 360, S and L in 0 to 100
  1135. */
  1136. protected function toRGB($color) {
  1137. if ($color[0] == 'color') return $color;
  1138. $H = $color[1] / 360;
  1139. $S = $color[2] / 100;
  1140. $L = $color[3] / 100;
  1141. if ($S == 0) {
  1142. $r = $g = $b = $L;
  1143. } else {
  1144. $temp2 = $L < 0.5 ?
  1145. $L*(1.0 + $S) :
  1146. $L + $S - $L * $S;
  1147. $temp1 = 2.0 * $L - $temp2;
  1148. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  1149. $g = $this->toRGB_helper($H, $temp1, $temp2);
  1150. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  1151. }
  1152. // $out = array('color', round($r*255), round($g*255), round($b*255));
  1153. $out = array('color', $r*255, $g*255, $b*255);
  1154. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  1155. return $out;
  1156. }
  1157. protected function clamp($v, $max = 1, $min = 0) {
  1158. return min($max, max($min, $v));
  1159. }
  1160. /**
  1161. * Convert the rgb, rgba, hsl color literals of function type
  1162. * as returned by the parser into values of color type.
  1163. */
  1164. protected function funcToColor($func) {
  1165. $fname = $func[1];
  1166. if ($func[2][0] != 'list') return false; // need a list of arguments
  1167. $rawComponents = $func[2][2];
  1168. if ($fname == 'hsl' || $fname == 'hsla') {
  1169. $hsl = array('hsl');
  1170. $i = 0;
  1171. foreach ($rawComponents as $c) {
  1172. $val = $this->reduce($c);
  1173. $val = isset($val[1]) ? floatval($val[1]) : 0;
  1174. if ($i == 0) $clamp = 360;
  1175. elseif ($i < 3) $clamp = 100;
  1176. else $clamp = 1;
  1177. $hsl[] = $this->clamp($val, $clamp);
  1178. $i++;
  1179. }
  1180. while (count($hsl) < 4) $hsl[] = 0;
  1181. return $this->toRGB($hsl);
  1182. } elseif ($fname == 'rgb' || $fname == 'rgba') {
  1183. $components = array();
  1184. $i = 1;
  1185. foreach ($rawComponents as $c) {
  1186. $c = $this->reduce($c);
  1187. if ($i < 4) {
  1188. if ($c[0] == "number" && $c[2] == "%") {
  1189. $components[] = 255 * ($c[1] / 100);
  1190. } else {
  1191. $components[] = floatval($c[1]);
  1192. }
  1193. } elseif ($i == 4) {
  1194. if ($c[0] == "number" && $c[2] == "%") {
  1195. $components[] = 1.0 * ($c[1] / 100);
  1196. } else {
  1197. $components[] = floatval($c[1]);
  1198. }
  1199. } else break;
  1200. $i++;
  1201. }
  1202. while (count($components) < 3) $components[] = 0;
  1203. array_unshift($components, 'color');
  1204. return $this->fixColor($components);
  1205. }
  1206. return false;
  1207. }
  1208. protected function reduce($value, $forExpression = false) {
  1209. switch ($value[0]) {
  1210. case "interpolate":
  1211. $reduced = $this->reduce($value[1]);
  1212. $var = $this->compileValue($reduced);
  1213. $res = $this->reduce(array("variable", $this->vPrefix . $var));
  1214. if ($res[0] == "raw_color") {
  1215. $res = $this->coerceColor($res);
  1216. }
  1217. if (empty($value[2])) $res = $this->lib_e($res);
  1218. return $res;
  1219. case "variable":
  1220. $key = $value[1];
  1221. if (is_array($key)) {
  1222. $key = $this->reduce($key);
  1223. $key = $this->vPrefix . $this->compileValue($this->lib_e($key));
  1224. }
  1225. $seen =& $this->env->seenNames;
  1226. if (!empty($seen[$key])) {
  1227. $this->throwError("infinite loop detected: $key");
  1228. }
  1229. $seen[$key] = true;
  1230. $out = $this->reduce($this->get($key));
  1231. $seen[$key] = false;
  1232. return $out;
  1233. case "list":
  1234. foreach ($value[2] as &$item) {
  1235. $item = $this->reduce($item, $forExpression);
  1236. }
  1237. return $value;
  1238. case "expression":
  1239. return $this->evaluate($value);
  1240. case "string":
  1241. foreach ($value[2] as &$part) {
  1242. if (is_array($part)) {
  1243. $strip = $part[0] == "variable";
  1244. $part = $this->reduce($part);
  1245. if ($strip) $part = $this->lib_e($part);
  1246. }
  1247. }
  1248. return $value;
  1249. case "escape":
  1250. list(,$inner) = $value;
  1251. return $this->lib_e($this->reduce($inner));
  1252. case "function":
  1253. $color = $this->funcToColor($value);
  1254. if ($color) return $color;
  1255. list(, $name, $args) = $value;
  1256. if ($name == "%") $name = "_sprintf";
  1257. $f = isset($this->libFunctions[$name]) ?
  1258. $this->libFunctions[$name] : array($this, 'lib_'.str_replace('-', '_', $name));
  1259. if (is_callable($f)) {
  1260. if ($args[0] == 'list')
  1261. $args = self::compressList($args[2], $args[1]);
  1262. $ret = call_user_func($f, $this->reduce($args, true), $this);
  1263. if (is_null($ret)) {
  1264. return array("string", "", array(
  1265. $name, "(", $args, ")"
  1266. ));
  1267. }
  1268. // convert to a typed value if the result is a php primitive
  1269. if (is_numeric($ret)) $ret = array('number', $ret, "");
  1270. elseif (!is_array($ret)) $ret = array('keyword', $ret);
  1271. return $ret;
  1272. }
  1273. // plain function, reduce args
  1274. $value[2] = $this->reduce($value[2]);
  1275. return $value;
  1276. case "unary":
  1277. list(, $op, $exp) = $value;
  1278. $exp = $this->reduce($exp);
  1279. if ($exp[0] == "number") {
  1280. switch ($op) {
  1281. case "+":
  1282. return $exp;
  1283. case "-":
  1284. $exp[1] *= -1;
  1285. return $exp;
  1286. }
  1287. }
  1288. return array("string", "", array($op, $exp));
  1289. }
  1290. if ($forExpression) {
  1291. switch ($value[0]) {
  1292. case "keyword":
  1293. if ($color = $this->coerceColor($value)) {
  1294. return $color;
  1295. }
  1296. break;
  1297. case "raw_color":
  1298. return $this->coerceColor($value);
  1299. }
  1300. }
  1301. return $value;
  1302. }
  1303. // coerce a value for use in color operation
  1304. protected function coerceColor($value) {
  1305. switch($value[0]) {
  1306. case 'color': return $value;
  1307. case 'raw_color':
  1308. $c = array("color", 0, 0, 0);
  1309. $colorStr = substr($value[1], 1);
  1310. $num = hexdec($colorStr);
  1311. $width = strlen($colorStr) == 3 ? 16 : 256;
  1312. for ($i = 3; $i > 0; $i--) { // 3 2 1
  1313. $t = $num % $width;
  1314. $num /= $width;
  1315. $c[$i] = $t * (256/$width) + $t * floor(16/$width);
  1316. }
  1317. return $c;
  1318. case 'keyword':
  1319. $name = $value[1];
  1320. if (isset(self::$cssColors[$name])) {
  1321. $rgba = explode(',', self::$cssColors[$name]);
  1322. if(isset($rgba[3]))
  1323. return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
  1324. return array('color', $rgba[0], $rgba[1], $rgba[2]);
  1325. }
  1326. return null;
  1327. }
  1328. }
  1329. // make something string like into a string
  1330. protected function coerceString($value) {
  1331. switch ($value[0]) {
  1332. case "string":
  1333. return $value;
  1334. case "keyword":
  1335. return array("string", "", array($value[1]));
  1336. }
  1337. return null;
  1338. }
  1339. // turn list of length 1 into value type
  1340. protected function flattenList($value) {
  1341. if ($value[0] == "list" && count($value[2]) == 1) {
  1342. return $this->flattenList($value[2][0]);
  1343. }
  1344. return $value;
  1345. }
  1346. public function toBool($a) {
  1347. if ($a) return self::$TRUE;
  1348. else return self::$FALSE;
  1349. }
  1350. // evaluate an expression
  1351. protected function evaluate($exp) {
  1352. list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
  1353. $left = $this->reduce($left, true);
  1354. $right = $this->reduce($right, true);
  1355. if ($leftColor = $this->coerceColor($left)) {
  1356. $left = $leftColor;
  1357. }
  1358. if ($rightColor = $this->coerceColor($right)) {
  1359. $right = $rightColor;
  1360. }
  1361. $ltype = $left[0];
  1362. $rtype = $right[0];
  1363. // operators that work on all types
  1364. if ($op == "and") {
  1365. return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
  1366. }
  1367. if ($op == "=") {
  1368. return $this->toBool($this->eq($left, $right) );
  1369. }
  1370. if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
  1371. return $str;
  1372. }
  1373. // type based operators
  1374. $fname = "op_${ltype}_${rtype}";
  1375. if (is_callable(array($this, $fname))) {
  1376. $out = $this->$fname($op, $left, $right);
  1377. if (!is_null($out)) return $out;
  1378. }
  1379. // make the expression look it did before being parsed
  1380. $paddedOp = $op;
  1381. if ($whiteBefore) $paddedOp = " " . $paddedOp;
  1382. if ($whiteAfter) $paddedOp .= " ";
  1383. return array("string", "", array($left, $paddedOp, $right));
  1384. }
  1385. protected function stringConcatenate($left, $right) {
  1386. if ($strLeft = $this->coerceString($left)) {
  1387. if ($right[0] == "string") {
  1388. $right[1] = "";
  1389. }
  1390. $strLeft[2][] = $right;
  1391. return $strLeft;
  1392. }
  1393. if ($strRight = $this->coerceString($right)) {
  1394. array_unshift($strRight[2], $left);
  1395. return $strRight;
  1396. }
  1397. }
  1398. // make sure a color's components don't go out of bounds
  1399. protected function fixColor($c) {
  1400. foreach (range(1, 3) as $i) {
  1401. if ($c[$i] < 0) $c[$i] = 0;
  1402. if ($c[$i] > 255) $c[$i] = 255;
  1403. }
  1404. return $c;
  1405. }
  1406. protected function op_number_color($op, $lft, $rgt) {
  1407. if ($op == '+' || $op == '*') {
  1408. return $this->op_color_number($op, $rgt, $lft);
  1409. }
  1410. }
  1411. protected function op_color_number($op, $lft, $rgt) {
  1412. if ($rgt[0] == '%') $rgt[1] /= 100;
  1413. return $this->op_color_color($op, $lft,
  1414. array_fill(1, count($lft) - 1, $rgt[1]));
  1415. }
  1416. protected function op_color_color($op, $left, $right) {
  1417. $out = array('color');
  1418. $max = count($left) > count($right) ? count($left) : count($right);
  1419. foreach (range(1, $max - 1) as $i) {
  1420. $lval = isset($left[$i]) ? $left[$i] : 0;
  1421. $rval = isset($right[$i]) ? $right[$i] : 0;
  1422. switch ($op) {
  1423. case '+':
  1424. $out[] = $lval + $rval;
  1425. break;
  1426. case '-':
  1427. $out[] = $lval - $rval;
  1428. break;
  1429. case '*':
  1430. $out[] = $lval * $rval;
  1431. break;
  1432. case '%':
  1433. $out[] = $lval % $rval;
  1434. break;
  1435. case '/':
  1436. if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
  1437. $out[] = $lval / $rval;
  1438. break;
  1439. default:
  1440. $this->throwError('evaluate error: color op number failed on op '.$op);
  1441. }
  1442. }
  1443. return $this->fixColor($out);
  1444. }
  1445. function lib_red($color){
  1446. $color = $this->coerceColor($color);
  1447. if (is_null($color)) {
  1448. $this->throwError('color expected for red()');
  1449. }
  1450. return $color[1];
  1451. }
  1452. function lib_green($color){
  1453. $color = $this->coerceColor($color);
  1454. if (is_null($color)) {
  1455. $this->throwError('color expected for green()');
  1456. }
  1457. return $color[2];
  1458. }
  1459. function lib_blue($color){
  1460. $color = $this->coerceColor($color);
  1461. if (is_null($color)) {
  1462. $this->throwError('color expected for blue()');
  1463. }
  1464. return $color[3];
  1465. }
  1466. // operator on two numbers
  1467. protected function op_number_number($op, $left, $right) {
  1468. $unit = empty($left[2]) ? $right[2] : $left[2];
  1469. $value = 0;
  1470. switch ($op) {
  1471. case '+':
  1472. $value = $left[1] + $right[1];
  1473. break;
  1474. case '*':
  1475. $value = $left[1] * $right[1];
  1476. break;
  1477. case '-':
  1478. $value = $left[1] - $right[1];
  1479. break;
  1480. case '%':
  1481. $value = $left[1] % $right[1];
  1482. break;
  1483. case '/':
  1484. if ($right[1] == 0) $this->throwError('parse error: divide by zero');
  1485. $value = $left[1] / $right[1];
  1486. break;
  1487. case '<':
  1488. return $this->toBool($left[1] < $right[1]);
  1489. case '>':
  1490. return $this->toBool($left[1] > $right[1]);
  1491. case '>=':
  1492. return $this->toBool($left[1] >= $right[1]);
  1493. case '=<':
  1494. return $this->toBool($left[1] <= $right[1]);
  1495. default:
  1496. $this->throwError('parse error: unknown number operator: '.$op);
  1497. }
  1498. return array("number", $value, $unit);
  1499. }
  1500. /* environment functions */
  1501. protected function makeOutputBlock($type, $selectors = null) {
  1502. $b = new stdclass;
  1503. $b->lines = array();
  1504. $b->children = array();
  1505. $b->selectors = $selectors;
  1506. $b->type = $type;
  1507. $b->parent = $this->scope;
  1508. return $b;
  1509. }
  1510. // the state of execution
  1511. protected function pushEnv($block = null) {
  1512. $e = new stdclass;
  1513. $e->parent = $this->env;
  1514. $e->store = array();
  1515. $e->block = $block;
  1516. $this->env = $e;
  1517. return $e;
  1518. }
  1519. // pop something off the stack
  1520. protected function popEnv() {
  1521. $old = $this->env;
  1522. $this->env = $this->env->parent;
  1523. return $old;
  1524. }
  1525. // set something in the current env
  1526. protected function set($name, $value) {
  1527. $this->env->store[$name] = $value;
  1528. }
  1529. // get the highest occurrence entry for a name
  1530. protected function get($name) {
  1531. $current = $this->env;
  1532. $isArguments = $name == $this->vPrefix . 'arguments';
  1533. while ($current) {
  1534. if ($isArguments && isset($current->arguments)) {
  1535. return array('list', ' ', $current->arguments);
  1536. }
  1537. if (isset($current->store[$name]))
  1538. return $current->store[$name];
  1539. else {
  1540. $current = isset($current->storeParent) ?
  1541. $current->storeParent : $current->parent;
  1542. }
  1543. }
  1544. $this->throwError("variable $name is undefined");
  1545. }
  1546. // inject array of unparsed strings into environment as variables
  1547. protected function injectVariables($args) {
  1548. $this->pushEnv();
  1549. $parser = new lessc_parser($this, __METHOD__);
  1550. foreach ($args as $name => $strValue) {
  1551. if ($name{0} != '@') $name = '@'.$name;
  1552. $parser->count = 0;
  1553. $parser->buffer = (string)$strValue;
  1554. if (!$parser->propertyValue($value)) {
  1555. throw new Exception("failed to parse passed in variable $name: $strValue");
  1556. }
  1557. $this->set($name, $value);
  1558. }
  1559. }
  1560. /**
  1561. * Initialize any static state, can initialize parser for a file
  1562. * $opts isn't used yet
  1563. */
  1564. public function __construct($fname = null) {
  1565. if ($fname !== null) {
  1566. // used for deprecated parse method
  1567. $this->_parseFile = $fname;
  1568. }
  1569. }
  1570. public function compile($string, $name = null) {
  1571. $locale = setlocale(LC_NUMERIC, 0);
  1572. setlocale(LC_NUMERIC, "C");
  1573. $this->parser = $this->makeParser($name);
  1574. $root = $this->parser->parse($string);
  1575. $this->env = null;
  1576. $this->scope = null;
  1577. $this->formatter = $this->newFormatter();
  1578. if (!empty($this->registeredVars)) {
  1579. $this->injectVariables($this->registeredVars);
  1580. }
  1581. $this->sourceParser = $this->parser; // used for error messages
  1582. $this->compileBlock($root);
  1583. ob_start();
  1584. $this->formatter->block($this->scope);
  1585. $out = ob_get_clean();
  1586. setlocale(LC_NUMERIC, $locale);
  1587. return $out;
  1588. }
  1589. public function compileFile($fname, $outFname = null) {
  1590. if (!is_readable($fname)) {
  1591. throw new Exception('load error: failed to find '.$fname);
  1592. }
  1593. $pi = pathinfo($fname);
  1594. $oldImport = $this->importDir;
  1595. $this->importDir = (array)$this->importDir;
  1596. $this->importDir[] = $pi['dirname'].'/';
  1597. $this->addParsedFile($fname);
  1598. $out = $this->compile(file_get_contents($fname), $fname);
  1599. $this->importDir = $oldImport;
  1600. if ($outFname !== null) {
  1601. return file_put_contents($outFname, $out);
  1602. }
  1603. return $out;
  1604. }
  1605. // compile only if changed input has changed or output doesn't exist
  1606. public function checkedCompile($in, $out) {
  1607. if (!is_file($out) || filemtime($in) > filemtime($out)) {
  1608. $this->compileFile($in, $out);
  1609. return true;
  1610. }
  1611. return false;
  1612. }
  1613. /**
  1614. * Execute lessphp on a .less file or a lessphp cache structure
  1615. *
  1616. * The lessphp cache structure contains information about a specific
  1617. * less file having been parsed. It can be used as a hint for future
  1618. * calls to determine whether or not a rebuild is required.
  1619. *
  1620. * Th…

Large files files are truncated, but you can click here to view the full file