PageRenderTime 116ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/p093_includes/vendor/leafo/lessphp/lessc.php

https://bitbucket.org/rlm3/rlm3_staging
PHP | 3676 lines | 2773 code | 570 blank | 333 comment | 643 complexity | 873a6516f9ed33f2821e748e3f7a1939 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, GPL-2.0, BSD-3-Clause, GPL-3.0, LGPL-2.1

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

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

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