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

/lib/lessphp/lessc.inc.php

https://bitbucket.org/tikapot/tikapot
PHP | 3358 lines | 2522 code | 516 blank | 320 comment | 581 complexity | b075ea15b26ef9c494e19d228d744f2d MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-3.0, LGPL-2.1

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

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

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