PageRenderTime 278ms CodeModel.GetById 25ms RepoModel.GetById 135ms app.codeStats 2ms

/min/lib/lessphp/lessc.inc.php

https://github.com/yorch/MinifyLessCSS
PHP | 3472 lines | 2613 code | 537 blank | 322 comment | 611 complexity | 72d1b56df39c22b0ea81b944f72a25b5 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-3.0

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

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

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