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

/lessc.inc.php

https://github.com/Gobler/lessphp
PHP | 3476 lines | 2616 code | 538 blank | 322 comment | 613 complexity | be5a25f056a2680dcd5896062780d12d MD5 | raw file
Possible License(s): 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. if ($mixin === $block && !$args) {
  534. continue;
  535. }
  536. $haveScope = false;
  537. if (isset($mixin->parent->scope)) {
  538. $haveScope = true;
  539. $mixinParentEnv = $this->pushEnv();
  540. $mixinParentEnv->storeParent = $mixin->parent->scope;
  541. }
  542. $haveArgs = false;
  543. if (isset($mixin->args)) {
  544. $haveArgs = true;
  545. $this->pushEnv();
  546. $this->zipSetArgs($mixin->args, $args);
  547. }
  548. $oldParent = $mixin->parent;
  549. if ($mixin != $block) $mixin->parent = $block;
  550. foreach ($this->sortProps($mixin->props) as $subProp) {
  551. if ($suffix !== null &&
  552. $subProp[0] == "assign" &&
  553. is_string($subProp[1]) &&
  554. $subProp[1]{0} != $this->vPrefix)
  555. {
  556. $subProp[2] = array(
  557. 'list', ' ',
  558. array($subProp[2], array('keyword', $suffix))
  559. );
  560. }
  561. $this->compileProp($subProp, $mixin, $out);
  562. }
  563. $mixin->parent = $oldParent;
  564. if ($haveArgs) $this->popEnv();
  565. if ($haveScope) $this->popEnv();
  566. }
  567. break;
  568. case 'raw':
  569. $out->lines[] = $prop[1];
  570. break;
  571. case "directive":
  572. list(, $name, $value) = $prop;
  573. $out->lines[] = "@$name " . $this->compileValue($this->reduce($value)).';';
  574. break;
  575. case "comment":
  576. $out->lines[] = $prop[1];
  577. break;
  578. case "import";
  579. list(, $importPath, $importId) = $prop;
  580. $importPath = $this->reduce($importPath);
  581. if (!isset($this->env->imports)) {
  582. $this->env->imports = array();
  583. }
  584. $result = $this->tryImport($importPath, $block, $out);
  585. $this->env->imports[$importId] = $result === false ?
  586. array(false, "@import " . $this->compileValue($importPath).";") :
  587. $result;
  588. break;
  589. case "import_mixin":
  590. list(,$importId) = $prop;
  591. $import = $this->env->imports[$importId];
  592. if ($import[0] === false) {
  593. $out->lines[] = $import[1];
  594. } else {
  595. list(, $bottom, $parser, $importDir) = $import;
  596. $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
  597. }
  598. break;
  599. default:
  600. $this->throwError("unknown op: {$prop[0]}\n");
  601. }
  602. }
  603. /**
  604. * Compiles a primitive value into a CSS property value.
  605. *
  606. * Values in lessphp are typed by being wrapped in arrays, their format is
  607. * typically:
  608. *
  609. * array(type, contents [, additional_contents]*)
  610. *
  611. * The input is expected to be reduced. This function will not work on
  612. * things like expressions and variables.
  613. */
  614. protected function compileValue($value) {
  615. switch ($value[0]) {
  616. case 'list':
  617. // [1] - delimiter
  618. // [2] - array of values
  619. return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
  620. case 'raw_color':
  621. if (!empty($this->formatter->compressColors)) {
  622. return $this->compileValue($this->coerceColor($value));
  623. }
  624. return $value[1];
  625. case 'keyword':
  626. // [1] - the keyword
  627. return $value[1];
  628. case 'number':
  629. list(, $num, $unit) = $value;
  630. // [1] - the number
  631. // [2] - the unit
  632. if ($this->numberPrecision !== null) {
  633. $num = round($num, $this->numberPrecision);
  634. }
  635. return $num . $unit;
  636. case 'string':
  637. // [1] - contents of string (includes quotes)
  638. list(, $delim, $content) = $value;
  639. foreach ($content as &$part) {
  640. if (is_array($part)) {
  641. $part = $this->compileValue($part);
  642. }
  643. }
  644. return $delim . implode($content) . $delim;
  645. case 'color':
  646. // [1] - red component (either number or a %)
  647. // [2] - green component
  648. // [3] - blue component
  649. // [4] - optional alpha component
  650. list(, $r, $g, $b) = $value;
  651. $r = round($r);
  652. $g = round($g);
  653. $b = round($b);
  654. if (count($value) == 5 && $value[4] != 1) { // rgba
  655. return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
  656. }
  657. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  658. if (!empty($this->formatter->compressColors)) {
  659. // Converting hex color to short notation (e.g. #003399 to #039)
  660. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  661. $h = '#' . $h[1] . $h[3] . $h[5];
  662. }
  663. }
  664. return $h;
  665. case 'function':
  666. list(, $name, $args) = $value;
  667. return $name.'('.$this->compileValue($args).')';
  668. default: // assumed to be unit
  669. $this->throwError("unknown value type: $value[0]");
  670. }
  671. }
  672. protected function lib_isnumber($value) {
  673. return $this->toBool($value[0] == "number");
  674. }
  675. protected function lib_isstring($value) {
  676. return $this->toBool($value[0] == "string");
  677. }
  678. protected function lib_iscolor($value) {
  679. return $this->toBool($this->coerceColor($value));
  680. }
  681. protected function lib_iskeyword($value) {
  682. return $this->toBool($value[0] == "keyword");
  683. }
  684. protected function lib_ispixel($value) {
  685. return $this->toBool($value[0] == "number" && $value[2] == "px");
  686. }
  687. protected function lib_ispercentage($value) {
  688. return $this->toBool($value[0] == "number" && $value[2] == "%");
  689. }
  690. protected function lib_isem($value) {
  691. return $this->toBool($value[0] == "number" && $value[2] == "em");
  692. }
  693. protected function lib_isrem($value) {
  694. return $this->toBool($value[0] == "number" && $value[2] == "rem");
  695. }
  696. protected function lib_rgbahex($color) {
  697. $color = $this->coerceColor($color);
  698. if (is_null($color))
  699. $this->throwError("color expected for rgbahex");
  700. return sprintf("#%02x%02x%02x%02x",
  701. isset($color[4]) ? $color[4]*255 : 255,
  702. $color[1],$color[2], $color[3]);
  703. }
  704. protected function lib_argb($color){
  705. return $this->lib_rgbahex($color);
  706. }
  707. // utility func to unquote a string
  708. protected function lib_e($arg) {
  709. switch ($arg[0]) {
  710. case "list":
  711. $items = $arg[2];
  712. if (isset($items[0])) {
  713. return $this->lib_e($items[0]);
  714. }
  715. return self::$defaultValue;
  716. case "string":
  717. $arg[1] = "";
  718. return $arg;
  719. case "keyword":
  720. return $arg;
  721. default:
  722. return array("keyword", $this->compileValue($arg));
  723. }
  724. }
  725. protected function lib__sprintf($args) {
  726. if ($args[0] != "list") return $args;
  727. $values = $args[2];
  728. $string = array_shift($values);
  729. $template = $this->compileValue($this->lib_e($string));
  730. $i = 0;
  731. if (preg_match_all('/%[dsa]/', $template, $m)) {
  732. foreach ($m[0] as $match) {
  733. $val = isset($values[$i]) ?
  734. $this->reduce($values[$i]) : array('keyword', '');
  735. // lessjs compat, renders fully expanded color, not raw color
  736. if ($color = $this->coerceColor($val)) {
  737. $val = $color;
  738. }
  739. $i++;
  740. $rep = $this->compileValue($this->lib_e($val));
  741. $template = preg_replace('/'.self::preg_quote($match).'/',
  742. $rep, $template, 1);
  743. }
  744. }
  745. $d = $string[0] == "string" ? $string[1] : '"';
  746. return array("string", $d, array($template));
  747. }
  748. protected function lib_floor($arg) {
  749. $value = $this->assertNumber($arg);
  750. return array("number", floor($value), $arg[2]);
  751. }
  752. protected function lib_ceil($arg) {
  753. $value = $this->assertNumber($arg);
  754. return array("number", ceil($value), $arg[2]);
  755. }
  756. protected function lib_round($arg) {
  757. $value = $this->assertNumber($arg);
  758. return array("number", round($value), $arg[2]);
  759. }
  760. protected function lib_unit($arg) {
  761. if ($arg[0] == "list") {
  762. list($number, $newUnit) = $arg[2];
  763. return array("number", $this->assertNumber($number),
  764. $this->compileValue($this->lib_e($newUnit)));
  765. } else {
  766. return array("number", $this->assertNumber($arg), "");
  767. }
  768. }
  769. /**
  770. * Helper function to get arguments for color manipulation functions.
  771. * takes a list that contains a color like thing and a percentage
  772. */
  773. protected function colorArgs($args) {
  774. if ($args[0] != 'list' || count($args[2]) < 2) {
  775. return array(array('color', 0, 0, 0), 0);
  776. }
  777. list($color, $delta) = $args[2];
  778. $color = $this->assertColor($color);
  779. $delta = floatval($delta[1]);
  780. return array($color, $delta);
  781. }
  782. protected function lib_darken($args) {
  783. list($color, $delta) = $this->colorArgs($args);
  784. $hsl = $this->toHSL($color);
  785. $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
  786. return $this->toRGB($hsl);
  787. }
  788. protected function lib_lighten($args) {
  789. list($color, $delta) = $this->colorArgs($args);
  790. $hsl = $this->toHSL($color);
  791. $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
  792. return $this->toRGB($hsl);
  793. }
  794. protected function lib_saturate($args) {
  795. list($color, $delta) = $this->colorArgs($args);
  796. $hsl = $this->toHSL($color);
  797. $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
  798. return $this->toRGB($hsl);
  799. }
  800. protected function lib_desaturate($args) {
  801. list($color, $delta) = $this->colorArgs($args);
  802. $hsl = $this->toHSL($color);
  803. $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
  804. return $this->toRGB($hsl);
  805. }
  806. protected function lib_spin($args) {
  807. list($color, $delta) = $this->colorArgs($args);
  808. $hsl = $this->toHSL($color);
  809. $hsl[1] = $hsl[1] + $delta % 360;
  810. if ($hsl[1] < 0) $hsl[1] += 360;
  811. return $this->toRGB($hsl);
  812. }
  813. protected function lib_fadeout($args) {
  814. list($color, $delta) = $this->colorArgs($args);
  815. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta/100);
  816. return $color;
  817. }
  818. protected function lib_fadein($args) {
  819. list($color, $delta) = $this->colorArgs($args);
  820. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta/100);
  821. return $color;
  822. }
  823. protected function lib_hue($color) {
  824. $hsl = $this->toHSL($this->assertColor($color));
  825. return round($hsl[1]);
  826. }
  827. protected function lib_saturation($color) {
  828. $hsl = $this->toHSL($this->assertColor($color));
  829. return round($hsl[2]);
  830. }
  831. protected function lib_lightness($color) {
  832. $hsl = $this->toHSL($this->assertColor($color));
  833. return round($hsl[3]);
  834. }
  835. // get the alpha of a color
  836. // defaults to 1 for non-colors or colors without an alpha
  837. protected function lib_alpha($value) {
  838. if (!is_null($color = $this->coerceColor($value))) {
  839. return isset($color[4]) ? $color[4] : 1;
  840. }
  841. }
  842. // set the alpha of the color
  843. protected function lib_fade($args) {
  844. list($color, $alpha) = $this->colorArgs($args);
  845. $color[4] = $this->clamp($alpha / 100.0);
  846. return $color;
  847. }
  848. protected function lib_percentage($arg) {
  849. $num = $this->assertNumber($arg);
  850. return array("number", $num*100, "%");
  851. }
  852. // mixes two colors by weight
  853. // mix(@color1, @color2, @weight);
  854. // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
  855. protected function lib_mix($args) {
  856. if ($args[0] != "list" || count($args[2]) < 3)
  857. $this->throwError("mix expects (color1, color2, weight)");
  858. list($first, $second, $weight) = $args[2];
  859. $first = $this->assertColor($first);
  860. $second = $this->assertColor($second);
  861. $first_a = $this->lib_alpha($first);
  862. $second_a = $this->lib_alpha($second);
  863. $weight = $weight[1] / 100.0;
  864. $w = $weight * 2 - 1;
  865. $a = $first_a - $second_a;
  866. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  867. $w2 = 1.0 - $w1;
  868. $new = array('color',
  869. $w1 * $first[1] + $w2 * $second[1],
  870. $w1 * $first[2] + $w2 * $second[2],
  871. $w1 * $first[3] + $w2 * $second[3],
  872. );
  873. if ($first_a != 1.0 || $second_a != 1.0) {
  874. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  875. }
  876. return $this->fixColor($new);
  877. }
  878. protected function lib_contrast($args) {
  879. if ($args[0] != 'list' || count($args[2]) < 3) {
  880. return array(array('color', 0, 0, 0), 0);
  881. }
  882. list($inputColor, $darkColor, $lightColor) = $args[2];
  883. $inputColor = $this->assertColor($inputColor);
  884. $darkColor = $this->assertColor($darkColor);
  885. $lightColor = $this->assertColor($lightColor);
  886. $hsl = $this->toHSL($inputColor);
  887. if ($hsl[3] > 50) {
  888. return $darkColor;
  889. }
  890. return $lightColor;
  891. }
  892. protected function assertColor($value, $error = "expected color value") {
  893. $color = $this->coerceColor($value);
  894. if (is_null($color)) $this->throwError($error);
  895. return $color;
  896. }
  897. protected function assertNumber($value, $error = "expecting number") {
  898. if ($value[0] == "number") return $value[1];
  899. $this->throwError($error);
  900. }
  901. protected function toHSL($color) {
  902. if ($color[0] == 'hsl') return $color;
  903. $r = $color[1] / 255;
  904. $g = $color[2] / 255;
  905. $b = $color[3] / 255;
  906. $min = min($r, $g, $b);
  907. $max = max($r, $g, $b);
  908. $L = ($min + $max) / 2;
  909. if ($min == $max) {
  910. $S = $H = 0;
  911. } else {
  912. if ($L < 0.5)
  913. $S = ($max - $min)/($max + $min);
  914. else
  915. $S = ($max - $min)/(2.0 - $max - $min);
  916. if ($r == $max) $H = ($g - $b)/($max - $min);
  917. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  918. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  919. }
  920. $out = array('hsl',
  921. ($H < 0 ? $H + 6 : $H)*60,
  922. $S*100,
  923. $L*100,
  924. );
  925. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  926. return $out;
  927. }
  928. protected function toRGB_helper($comp, $temp1, $temp2) {
  929. if ($comp < 0) $comp += 1.0;
  930. elseif ($comp > 1) $comp -= 1.0;
  931. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  932. if (2 * $comp < 1) return $temp2;
  933. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  934. return $temp1;
  935. }
  936. /**
  937. * Converts a hsl array into a color value in rgb.
  938. * Expects H to be in range of 0 to 360, S and L in 0 to 100
  939. */
  940. protected function toRGB($color) {
  941. if ($color[0] == 'color') return $color;
  942. $H = $color[1] / 360;
  943. $S = $color[2] / 100;
  944. $L = $color[3] / 100;
  945. if ($S == 0) {
  946. $r = $g = $b = $L;
  947. } else {
  948. $temp2 = $L < 0.5 ?
  949. $L*(1.0 + $S) :
  950. $L + $S - $L * $S;
  951. $temp1 = 2.0 * $L - $temp2;
  952. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  953. $g = $this->toRGB_helper($H, $temp1, $temp2);
  954. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  955. }
  956. // $out = array('color', round($r*255), round($g*255), round($b*255));
  957. $out = array('color', $r*255, $g*255, $b*255);
  958. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  959. return $out;
  960. }
  961. protected function clamp($v, $max = 1, $min = 0) {
  962. return min($max, max($min, $v));
  963. }
  964. /**
  965. * Convert the rgb, rgba, hsl color literals of function type
  966. * as returned by the parser into values of color type.
  967. */
  968. protected function funcToColor($func) {
  969. $fname = $func[1];
  970. if ($func[2][0] != 'list') return false; // need a list of arguments
  971. $rawComponents = $func[2][2];
  972. if ($fname == 'hsl' || $fname == 'hsla') {
  973. $hsl = array('hsl');
  974. $i = 0;
  975. foreach ($rawComponents as $c) {
  976. $val = $this->reduce($c);
  977. $val = isset($val[1]) ? floatval($val[1]) : 0;
  978. if ($i == 0) $clamp = 360;
  979. elseif ($i < 3) $clamp = 100;
  980. else $clamp = 1;
  981. $hsl[] = $this->clamp($val, $clamp);
  982. $i++;
  983. }
  984. while (count($hsl) < 4) $hsl[] = 0;
  985. return $this->toRGB($hsl);
  986. } elseif ($fname == 'rgb' || $fname == 'rgba') {
  987. $components = array();
  988. $i = 1;
  989. foreach ($rawComponents as $c) {
  990. $c = $this->reduce($c);
  991. if ($i < 4) {
  992. if ($c[0] == "number" && $c[2] == "%") {
  993. $components[] = 255 * ($c[1] / 100);
  994. } else {
  995. $components[] = floatval($c[1]);
  996. }
  997. } elseif ($i == 4) {
  998. if ($c[0] == "number" && $c[2] == "%") {
  999. $components[] = 1.0 * ($c[1] / 100);
  1000. } else {
  1001. $components[] = floatval($c[1]);
  1002. }
  1003. } else break;
  1004. $i++;
  1005. }
  1006. while (count($components) < 3) $components[] = 0;
  1007. array_unshift($components, 'color');
  1008. return $this->fixColor($components);
  1009. }
  1010. return false;
  1011. }
  1012. protected function reduce($value, $forExpression = false) {
  1013. switch ($value[0]) {
  1014. case "interpolate":
  1015. $reduced = $this->reduce($value[1]);
  1016. $var = $this->compileValue($reduced);
  1017. $res = $this->reduce(array("variable", $this->vPrefix . $var));
  1018. if (empty($value[2])) $res = $this->lib_e($res);
  1019. return $res;
  1020. case "variable":
  1021. $key = $value[1];
  1022. if (is_array($key)) {
  1023. $key = $this->reduce($key);
  1024. $key = $this->vPrefix . $this->compileValue($this->lib_e($key));
  1025. }
  1026. $seen =& $this->env->seenNames;
  1027. if (!empty($seen[$key])) {
  1028. $this->throwError("infinite loop detected: $key");
  1029. }
  1030. $seen[$key] = true;
  1031. $out = $this->reduce($this->get($key, self::$defaultValue));
  1032. $seen[$key] = false;
  1033. return $out;
  1034. case "list":
  1035. foreach ($value[2] as &$item) {
  1036. $item = $this->reduce($item, $forExpression);
  1037. }
  1038. return $value;
  1039. case "expression":
  1040. return $this->evaluate($value);
  1041. case "string":
  1042. foreach ($value[2] as &$part) {
  1043. if (is_array($part)) {
  1044. $strip = $part[0] == "variable";
  1045. $part = $this->reduce($part);
  1046. if ($strip) $part = $this->lib_e($part);
  1047. }
  1048. }
  1049. return $value;
  1050. case "escape":
  1051. list(,$inner) = $value;
  1052. return $this->lib_e($this->reduce($inner));
  1053. case "function":
  1054. $color = $this->funcToColor($value);
  1055. if ($color) return $color;
  1056. list(, $name, $args) = $value;
  1057. if ($name == "%") $name = "_sprintf";
  1058. $f = isset($this->libFunctions[$name]) ?
  1059. $this->libFunctions[$name] : array($this, 'lib_'.$name);
  1060. if (is_callable($f)) {
  1061. if ($args[0] == 'list')
  1062. $args = self::compressList($args[2], $args[1]);
  1063. $ret = call_user_func($f, $this->reduce($args, true), $this);
  1064. if (is_null($ret)) {
  1065. return array("string", "", array(
  1066. $name, "(", $args, ")"
  1067. ));
  1068. }
  1069. // convert to a typed value if the result is a php primitive
  1070. if (is_numeric($ret)) $ret = array('number', $ret, "");
  1071. elseif (!is_array($ret)) $ret = array('keyword', $ret);
  1072. return $ret;
  1073. }
  1074. // plain function, reduce args
  1075. $value[2] = $this->reduce($value[2]);
  1076. return $value;
  1077. case "unary":
  1078. list(, $op, $exp) = $value;
  1079. $exp = $this->reduce($exp);
  1080. if ($exp[0] == "number") {
  1081. switch ($op) {
  1082. case "+":
  1083. return $exp;
  1084. case "-":
  1085. $exp[1] *= -1;
  1086. return $exp;
  1087. }
  1088. }
  1089. return array("string", "", array($op, $exp));
  1090. }
  1091. if ($forExpression) {
  1092. switch ($value[0]) {
  1093. case "keyword":
  1094. if ($color = $this->coerceColor($value)) {
  1095. return $color;
  1096. }
  1097. break;
  1098. case "raw_color":
  1099. return $this->coerceColor($value);
  1100. }
  1101. }
  1102. return $value;
  1103. }
  1104. // coerce a value for use in color operation
  1105. protected function coerceColor($value) {
  1106. switch($value[0]) {
  1107. case 'color': return $value;
  1108. case 'raw_color':
  1109. $c = array("color", 0, 0, 0);
  1110. $colorStr = substr($value[1], 1);
  1111. $num = hexdec($colorStr);
  1112. $width = strlen($colorStr) == 3 ? 16 : 256;
  1113. for ($i = 3; $i > 0; $i--) { // 3 2 1
  1114. $t = $num % $width;
  1115. $num /= $width;
  1116. $c[$i] = $t * (256/$width) + $t * floor(16/$width);
  1117. }
  1118. return $c;
  1119. case 'keyword':
  1120. $name = $value[1];
  1121. if (isset(self::$cssColors[$name])) {
  1122. $rgba = explode(',', self::$cssColors[$name]);
  1123. if(isset($rgba[3]))
  1124. return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
  1125. return array('color', $rgba[0], $rgba[1], $rgba[2]);
  1126. }
  1127. return null;
  1128. }
  1129. }
  1130. // make something string like into a string
  1131. protected function coerceString($value) {
  1132. switch ($value[0]) {
  1133. case "string":
  1134. return $value;
  1135. case "keyword":
  1136. return array("string", "", array($value[1]));
  1137. }
  1138. return null;
  1139. }
  1140. // turn list of length 1 into value type
  1141. protected function flattenList($value) {
  1142. if ($value[0] == "list" && count($value[2]) == 1) {
  1143. return $this->flattenList($value[2][0]);
  1144. }
  1145. return $value;
  1146. }
  1147. protected function toBool($a) {
  1148. if ($a) return self::$TRUE;
  1149. else return self::$FALSE;
  1150. }
  1151. // evaluate an expression
  1152. protected function evaluate($exp) {
  1153. list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
  1154. $left = $this->reduce($left, true);
  1155. $right = $this->reduce($right, true);
  1156. if ($leftColor = $this->coerceColor($left)) {
  1157. $left = $leftColor;
  1158. }
  1159. if ($rightColor = $this->coerceColor($right)) {
  1160. $right = $rightColor;
  1161. }
  1162. $ltype = $left[0];
  1163. $rtype = $right[0];
  1164. // operators that work on all types
  1165. if ($op == "and") {
  1166. return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
  1167. }
  1168. if ($op == "=") {
  1169. return $this->toBool($this->eq($left, $right) );
  1170. }
  1171. if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
  1172. return $str;
  1173. }
  1174. // type based operators
  1175. $fname = "op_${ltype}_${rtype}";
  1176. if (is_callable(array($this, $fname))) {
  1177. $out = $this->$fname($op, $left, $right);
  1178. if (!is_null($out)) return $out;
  1179. }
  1180. // make the expression look it did before being parsed
  1181. $paddedOp = $op;
  1182. if ($whiteBefore) $paddedOp = " " . $paddedOp;
  1183. if ($whiteAfter) $paddedOp .= " ";
  1184. return array("string", "", array($left, $paddedOp, $right));
  1185. }
  1186. protected function stringConcatenate($left, $right) {
  1187. if ($strLeft = $this->coerceString($left)) {
  1188. if ($right[0] == "string") {
  1189. $right[1] = "";
  1190. }
  1191. $strLeft[2][] = $right;
  1192. return $strLeft;
  1193. }
  1194. if ($strRight = $this->coerceString($right)) {
  1195. array_unshift($strRight[2], $left);
  1196. return $strRight;
  1197. }
  1198. }
  1199. // make sure a color's components don't go out of bounds
  1200. protected function fixColor($c) {
  1201. foreach (range(1, 3) as $i) {
  1202. if ($c[$i] < 0) $c[$i] = 0;
  1203. if ($c[$i] > 255) $c[$i] = 255;
  1204. }
  1205. return $c;
  1206. }
  1207. protected function op_number_color($op, $lft, $rgt) {
  1208. if ($op == '+' || $op == '*') {
  1209. return $this->op_color_number($op, $rgt, $lft);
  1210. }
  1211. }
  1212. protected function op_color_number($op, $lft, $rgt) {
  1213. if ($rgt[0] == '%') $rgt[1] /= 100;
  1214. return $this->op_color_color($op, $lft,
  1215. array_fill(1, count($lft) - 1, $rgt[1]));
  1216. }
  1217. protected function op_color_color($op, $left, $right) {
  1218. $out = array('color');
  1219. $max = count($left) > count($right) ? count($left) : count($right);
  1220. foreach (range(1, $max - 1) as $i) {
  1221. $lval = isset($left[$i]) ? $left[$i] : 0;
  1222. $rval = isset($right[$i]) ? $right[$i] : 0;
  1223. switch ($op) {
  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. $out[] = $lval % $rval;
  1235. break;
  1236. case '/':
  1237. if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
  1238. $out[] = $lval / $rval;
  1239. break;
  1240. default:
  1241. $this->throwError('evaluate error: color op number failed on op '.$op);
  1242. }
  1243. }
  1244. return $this->fixColor($out);
  1245. }
  1246. function lib_red($color){
  1247. $color = $this->coerceColor($color);
  1248. if (is_null($color)) {
  1249. $this->throwError('color expected for red()');
  1250. }
  1251. return $color[1];
  1252. }
  1253. function lib_green($color){
  1254. $color = $this->coerceColor($color);
  1255. if (is_null($color)) {
  1256. $this->throwError('color expected for green()');
  1257. }
  1258. return $color[2];
  1259. }
  1260. function lib_blue($color){
  1261. $color = $this->coerceColor($color);
  1262. if (is_null($color)) {
  1263. $this->throwError('color expected for blue()');
  1264. }
  1265. return $color[3];
  1266. }
  1267. // operator on two numbers
  1268. protected function op_number_number($op, $left, $right) {
  1269. $unit = empty($left[2]) ? $right[2] : $left[2];
  1270. $value = 0;
  1271. switch ($op) {
  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. $value = $left[1] % $right[1];
  1283. break;
  1284. case '/':
  1285. if ($right[1] == 0) $this->throwError('parse error: divide by zero');
  1286. $value = $left[1] / $right[1];
  1287. break;
  1288. case '<':
  1289. return $this->toBool($left[1] < $right[1]);
  1290. case '>':
  1291. return $this->toBool($left[1] > $right[1]);
  1292. case '>=':
  1293. return $this->toBool($left[1] >= $right[1]);
  1294. case '=<':
  1295. return $this->toBool($left[1] <= $right[1]);
  1296. default:
  1297. $this->throwError('parse error: unknown number operator: '.$op);
  1298. }
  1299. return array("number", $value, $unit);
  1300. }
  1301. /* environment functions */
  1302. protected function makeOutputBlock($type, $selectors = null) {
  1303. $b = new stdclass;
  1304. $b->lines = array();
  1305. $b->children = array();
  1306. $b->selectors = $selectors;
  1307. $b->type = $type;
  1308. $b->parent = $this->scope;
  1309. return $b;
  1310. }
  1311. // the state of execution
  1312. protected function pushEnv($block = null) {
  1313. $e = new stdclass;
  1314. $e->parent = $this->env;
  1315. $e->store = array();
  1316. $e->block = $block;
  1317. $this->env = $e;
  1318. return $e;
  1319. }
  1320. // pop something off the stack
  1321. protected function popEnv() {
  1322. $old = $this->env;
  1323. $this->env = $this->env->parent;
  1324. return $old;
  1325. }
  1326. // set something in the current env
  1327. protected function set($name, $value) {
  1328. $this->env->store[$name] = $value;
  1329. }
  1330. // get the highest occurrence entry for a name
  1331. protected function get($name, $default=null) {
  1332. $current = $this->env;
  1333. $isArguments = $name == $this->vPrefix . 'arguments';
  1334. while ($current) {
  1335. if ($isArguments && isset($current->arguments)) {
  1336. return array('list', ' ', $current->arguments);
  1337. }
  1338. if (isset($current->store[$name]))
  1339. return $current->store[$name];
  1340. else {
  1341. $current = isset($current->storeParent) ?
  1342. $current->storeParent : $current->parent;
  1343. }
  1344. }
  1345. return $default;
  1346. }
  1347. // inject array of unparsed strings into environment as variables
  1348. protected function injectVariables($args) {
  1349. $this->pushEnv();
  1350. $parser = new lessc_parser($this, __METHOD__);
  1351. foreach ($args as $name => $strValue) {
  1352. if ($name{0} != '@') $name = '@'.$name;
  1353. $parser->count = 0;
  1354. $parser->buffer = (string)$strValue;
  1355. if (!$parser->propertyValue($value)) {
  1356. throw new Exception("failed to parse passed in variable $name: $strValue");
  1357. }
  1358. $this->set($name, $value);
  1359. }
  1360. }
  1361. /**
  1362. * Initialize any static state, can initialize parser for a file
  1363. * $opts isn't used yet
  1364. */
  1365. public function __construct($fname = null) {
  1366. if ($fname !== null) {
  1367. // used for deprecated parse method
  1368. $this->_parseFile = $fname;
  1369. }
  1370. }
  1371. public function compile($string, $name = null) {
  1372. $locale = setlocale(LC_NUMERIC, 0);
  1373. setlocale(LC_NUMERIC, "C");
  1374. $this->parser = $this->makeParser($name);
  1375. $root = $this->parser->parse($string);
  1376. $this->env = null;
  1377. $this->scope = null;
  1378. $this->formatter = $this->newFormatter();
  1379. if (!empty($this->registeredVars)) {
  1380. $this->injectVariables($this->registeredVars);
  1381. }
  1382. $this->sourceParser = $this->parser; // used for error messages
  1383. $this->compileBlock($root);
  1384. ob_start();
  1385. $this->formatter->block($this->scope);
  1386. $out = ob_get_clean();
  1387. setlocale(LC_NUMERIC, $locale);
  1388. return $out;
  1389. }
  1390. public function compileFile($fname, $outFname = null) {
  1391. if (!is_readable($fname)) {
  1392. throw new Exception('load error: failed to find '.$fname);
  1393. }
  1394. $pi = pathinfo($fname);
  1395. $oldImport = $this->importDir;
  1396. $this->importDir = (array)$this->importDir;
  1397. $this->importDir[] = $pi['dirname'].'/';
  1398. $this->allParsedFiles = array();
  1399. $this->addParsedFile($fname);
  1400. $out = $this->compile(file_get_contents($fname), $fname);
  1401. $this->importDir = $oldImport;
  1402. if ($outFname !== null) {
  1403. return file_put_contents($outFname, $out);
  1404. }
  1405. return $out;
  1406. }
  1407. // compile only if changed input has changed or output doesn't exist
  1408. public function checkedCompile($in, $out) {
  1409. if (!is_file($out) || filemtime($in) > filemtime($out)) {
  1410. $this->compileFile($in, $out);
  1411. return true;
  1412. }
  1413. return false;
  1414. }
  1415. /**
  1416. * Execute lessphp on a .less file or a lessphp cache structure
  1417. *
  1418. * The lessphp cache structure contains information about a specific
  1419. * less file having been parsed. It can be used as a hint for future
  1420. * calls to determine whether or not a rebuild is required.
  1421. *
  1422. * The cache structure contains two important keys that may be used
  1423. * externally:
  1424. *
  1425. * compiled: The final compiled CSS
  1426. * updated: The time (in seconds) the CSS was last compiled
  1427. *
  1428. * The cache structure is a plain-ol' PHP associative array and can
  1429. * be serialized and unserialized without a hitch.
  1430. *
  1431. * @param mixed $in Input
  1432. * @param bool $force Force rebuild?
  1433. * @return array lessphp cache structure
  1434. */
  1435. public function cachedCompile($in, $force = false) {
  1436. // assume no root
  1437. $root = null;
  1438. if (is_string($in)) {
  1439. $root = $in;
  1440. } elseif (is_array($in) and isset($in['root'])) {
  1441. if ($force or ! isset($in['files'])) {
  1442. // If we are forcing a recompile or if for some reason the
  1443. // structure does not contain any file information we should
  1444. // specify the root to trigger a rebuild.
  1445. $root = $in['root'];
  1446. } elseif (isset($in['files']) and is_array($in['files'])) {
  1447. foreach ($in['files'] as $fname => $ftime ) {
  1448. if (!file_exists($fname) or filemtime($fname) > $ftime) {
  1449. // One of the files we knew about previously has changed
  1450. // so we should look at our incoming root again.
  1451. $root = $in['root'];
  1452. break;
  1453. }
  1454. }
  1455. }
  1456. } else {
  1457. // TODO: Throw an exception? We got neither a string nor something
  1458. // that looks like a compatible lessphp cache structure.
  1459. return null;
  1460. }
  1461. if ($root !== null) {
  1462. // If we have a root value which means we should rebuild.
  1463. $out = array();
  1464. $out['root'] = $root;
  1465. $out['compiled'] = $this->compileFile($root);
  1466. $out['files'] = $this->allParsedFiles();
  1467. $out['updated'] = time();
  1468. return $out;
  1469. } else {
  1470. // No changes, pass back the structure
  1471. // we were given initially.
  1472. return $in;
  1473. }
  1474. }
  1475. // parse and compile buffer
  1476. // This is deprecated
  1477. public function parse($str = null, $initialVariables = null) {
  1478. if (is_array($str)) {
  1479. $initialVariables = $str;
  1480. $str = null;
  1481. }
  1482. $oldVars = $this->registeredVars;
  1483. if ($initialVariables !== null) {
  1484. $this->setVariables($initialVariables);
  1485. }
  1486. if ($str == null) {
  1487. if (empty($this->_parseFile)) {
  1488. throw new exception("nothing to parse");
  1489. }
  1490. $out = $this->compileFile($this->_parseFile);
  1491. } else {
  1492. $out = $this->compile($str);
  1493. }
  1494. $this->registeredVars = $oldVars;
  1495. return $out;
  1496. }
  1497. protected function makeParser($name) {
  1498. $parser = new lessc_parser($this, $name);
  1499. $parser->writeComments = $this->preserveComments;
  1500. return $parser;
  1501. }
  1502. public function setFormatter($name) {
  1503. $this->formatterName = $name;
  1504. }
  1505. protected function newFormatter() {
  1506. $className = "lessc_formatter_lessjs";
  1507. if (!empty($this->formatterName)) {
  1508. if (!is_string($this->formatterName))
  1509. return $this->formatterName;
  1510. $className = "lessc_formatter_$this->formatterName";
  1511. }
  1512. return new $className;
  1513. }
  1514. public function setPreserveComments($preserve) {
  1515. $this->preserveComments = $preserve;
  1516. }
  1517. public function registerFunction($name, $func) {
  1518. $this->libFunctions[$name] = $func;
  1519. }
  1520. public function unregisterFunction($name) {
  1521. unset($this->libFunctions[$name]);
  1522. }
  1523. public function setVariables($variables) {
  1524. $this->registeredVars = array_merge($this->registeredVars, $variables);
  1525. }
  1526. public function unsetVariable($name) {
  1527. unset($this->registeredVars[$name]);
  1528. }
  1529. public function setImportDir($dirs) {
  1530. $this->importDir = (array)$dirs;
  1531. }
  1532. public function addImportDir($dir) {
  1533. $this->importDir = (array)$this->importDir;
  1534. $this->importDir[] = $dir;
  1535. }
  1536. public function allParsedFiles() {
  1537. return $this->allParsedFiles;
  1538. }
  1539. protected function addParsedFile($file) {
  1540. $this->allParsedFiles[realpath($file)] = filemtime($file);
  1541. }
  1542. /**
  1543. * Uses the current value of $this->count to show line and line number
  1544. */
  1545. protected function throwError($msg = null) {
  1546. if ($this->sourceLoc >= 0) {
  1547. $this->sourceParser->throwError($msg, $this->sourceLoc);
  1548. }
  1549. throw new exception($msg);
  1550. }
  1551. // compile file $in to file $out if $in is newer than $out
  1552. // returns true when it compiles, false otherwise
  1553. public static function ccompile($in, $out, $less = null) {
  1554. if ($less === null) {
  1555. $less = new self;
  1556. }
  1557. return $less->checkedCompile($in, $out);
  1558. }
  1559. public static function cexecute($in, $force = false, $less = null) {
  1560. if ($less === null) {
  1561. $less = new self;
  1562. }
  1563. return $less->cachedCompile($in, $force);
  1564. }
  1565. static protected $cssColors = array(
  1566. 'aliceblue' => '240,248,255',
  1567. 'antiquewhite' => '250,235,215',
  1568. 'aqua' => '0,255,255',
  1569. 'aquamarine' => '127,255,212',
  1570. 'azure' => '240,255,255',
  1571. 'beige' => '245,245,220',
  1572. 'bisque' => '255,228,196',
  1573. 'black' => '0,0,0',
  1574. 'blanchedalmond' => '255,235,205',
  1575. 'blue' => '0,0,255',
  1576. 'blueviolet' => '138,43,226',
  1577. 'brown' => '165,42,42',
  1578. 'burlywood' => '222,184,135',
  1579. 'cadetblue' => '95,158,160',
  1580. 'chartreuse' => '127,255,0',
  1581. 'chocolate' => '210,105,30',
  1582. 'coral' => '255,127,80',
  1583. 'cornflowerblue' => '100,149,237',
  1584. 'cornsilk' => '255,248,220',
  1585. 'crimson' => '220,20,60',
  1586. 'cyan' => '0,255,255',
  1587. 'darkblue' => '0,0,139',
  1588. 'darkcyan' => '0,139,139',
  1589. 'darkgoldenrod' => '184,134,11',
  1590. 'darkgray' => '169,169,169',
  1591. 'darkgreen' => '0,100,0',
  1592. 'darkgrey' => '169,169,169',
  1593. 'darkkhaki' => '189,183,107',
  1594. 'darkmagenta' => '139,0,139',
  1595. 'darkolivegreen' => '85,107,47',
  1596. 'darkorange' => '255,140,0',
  1597. 'darkorchid' => '153,50,204',
  1598. 'darkred' => '139,0,0',
  1599. 'darksalmon' => '233,150,122',
  1600. 'darkseagreen' => '143,188,143',
  1601. 'darkslateblue' => '72,61,139',
  1602. 'darkslategray' => '47,79,79',
  1603. 'darkslategrey' => '47,79,79',
  1604. 'darkturquoise' => '0,206,209',
  1605. 'darkviolet' => '148,0,211',
  1606. 'deeppink' => '255,20,147',
  1607. 'deepskyblue' => '0,191,255',
  1608. 'dimgray' => '105,105,105',
  1609. 'dimgrey' => '105,105,105',
  1610. 'dodgerblue' => '30,144,255',
  1611. 'firebrick' => '178,34,34',
  1612. 'floralwhite' => '255,250,240',
  1613. 'forestgreen' => '34,139,34',
  1614. 'fuchsia' => '255,0,255',
  1615. 'gainsboro' => '220,220,220',
  1616. 'ghostwhite' => '248,248,255',
  1617. 'gold' => '255,215,0',
  1618. 'goldenrod' => '218,165,32',
  1619. 'gray' => '128,128,128',
  1620. 'green' => '0,128,0',
  1621. 'greenyellow' => '173,255,47',
  1622. 'grey' => '128,128,128',
  1623. 'honeydew' => '240,255,240',
  1624. 'hotpink' => '255,105,180',
  1625. 'indianred' => '205,92,92',
  1626. 'indigo' => '75,0,130',
  1627. 'ivory' => '255,255,240',
  1628. 'khaki' => '240,230,140',
  1629. 'lavender' => '230,230,250',
  1630. 'lavenderblush' => '255,240,245',
  1631. 'lawngreen' => '124,252,0',
  1632. 'lemonchiffon' => '255,250,205',
  1633. 'lightblue' => '173,216,230',
  1634. 'lightcoral' => '240,128,128',
  1635. 'lightcyan' => '224,255,255',
  1636. 'lightgoldenrodyellow' => '250,250,210',
  1637. 'lightgray' => '211,211,211',
  1638. 'lightgreen…

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